Solved

Inserting and updating a post manually without using the admin panel

Posted on 2014-02-16
4
283 Views
Last Modified: 2014-03-01
Hi

I am trying to work out how i would insert or update a post manually without using the admin panel

I have found the function wp_insert_post in post.php file

Questions
1) Is this a standalone function or part of some class. Im not a php programmer
2) It uses global $wpdb and then uses this object through the function e,g, $wpdb->insert_id;
If i wanted to connect to a different wordpress database could i do this $wpdb= new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST) inside the wp_insert_post function.

Naturally I will go off and try these things but i dont want to be barking up the wrong tree :)

Thanks
0
Comment
Question by:andieje
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 

Expert Comment

by:mokaid83
ID: 39862706
why dont you try to use the PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions

http://www.php.net/PDO
0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 39862913
I have just started experimenting with WP.  I wrote a plugin that will create a map of the USA showing where visitors come from.  Not sure whether it will be helpful to you, but you can see how I used the wpdb stuff in a fairly basic way.  Look in functions visitmapper_install(), visitmapper_insert() and visitmapper_map().

<?php
/**
 * Plugin Name: Visit Mapper
 * Plugin URI: NOT PUBLISHED YET AT http://wordpress.org/plugins/visitmapper/
 * Description: Records the Geocodes (lat,lon) of Site Visitors
 * Version: 0.1
 * Author: Ray Paseur
 * Author URI: http://www.linkedin.com/profile/view?id=2122892
 * License: GPL2
 */


// VISITMAPPER PLUG-IN
global $wpdb;
global $visitmapper_db_version;
$visitmapper_db_version = "0.1";

function visitmapper_install()
{

    global $wpdb;
    global $table_name;
    $table_name = $wpdb->prefix . "visitmapper";

    // THIS STRUCTURE IS VERY RIGID - FOLLOW CLOSELY http://codex.wordpress.org/Creating_Tables_with_Plugins
    $sql = "CREATE TABLE $table_name (
id   INT NOT NULL AUTO_INCREMENT,
dov  DATETIME,
lat  DECIMAL(8,4) NOT NULL DEFAULT '0.0',
lon  DECIMAL(8,4) NOT NULL DEFAULT '0.0',
PRIMARY KEY  (id),
UNIQUE (lat, lon)
);";

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    $wpdb->query($sql);

    add_option( "visitmapper_db_version", $visitmapper_db_version );
} // END FUNCTION VISITMAPPER_install

register_activation_hook(__FILE__, 'visitmapper_install');

/**
 * MAKES A CURL GET REQUEST WITH A SHORT TIMEOUT
 */
function visitmapper_insert()
{
    global $wpdb;
    global $table_name;
    $table_name = $wpdb->prefix . "visitmapper";

    // THIS IS THE CLIENT IP ADDRESS
    $ipa = (!empty($_SERVER['REMOTE_ADDR'])) ?  $_SERVER['REMOTE_ADDR'] : NULL;
    if (!$ipa) return;

    // THIS IS THE URL FOR THE API, INCLUDING THE API KEY
    $url = 'http://api.geoio.com/q.php?key=cabMi8TqEJlzhDlw&qt=geoip&d=pipe&q=' . $ipa;

    // READ THE DATA FROM THE API
    $dat = visitmapper_curl_get($url);
    if (!$dat) return;

    // IF TOO MANY API CALLS TODAY
	if (strpos($dat, "MAX CONNECTIONS REACHED") !== FALSE) return;

	// BREAK RESPONSE APART AT PIPES
	$inf = explode('|', $dat);
	if ($inf[0] . $inf[1] == NULL) return;

	// RECORD THE INFORMATION IF IT IS AVAILABLE
	$lat = isset($inf[4]) ? $inf[4] : NULL;
	$lon = isset($inf[5]) ? $inf[5] : NULL;
	$geo = $lat . $lon;
	if (!$geo) return;

	$dov = date('c');

	// http://codex.wordpress.org/Class_Reference/wpdb
	// SET UP THE INSERT ARRAY (DEFAULT TO STRINGS)
	$ins = array
	( 'dov' => $dov
	, 'lat' => $lat
	, 'lon' => $lon
	)
	;
	// IGNORE DUPLICATE (1062) ERRORS
	$wpdb->hide_errors();
	$wpdb->insert($table_name, $ins);

	// NO NEED TO PRODUCE ANY OUTPUT HERE
	return;
}

// ADD FUNCTION TO THE FOOTER
add_action( 'get_footer', 'visitmapper_insert' );


// A FUNCTION TO RUN A CURL-GET CLIENT CALL TO A FOREIGN SERVER
function visitmapper_curl_get
( $url
, $timeout=1
, $error_report=FALSE
)
{
    // ASSUMES URL CONTAINS THE ARGUMENT STRING IF NEEDED
    $curl = curl_init();

    // HEADERS AND OPTIONS APPEAR TO BE A FIREFOX BROWSER REFERRED BY GOOGLE
    $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Keep-Alive: 300";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Pragma: "; // BROWSERS USUALLY LEAVE BLANK

    // SET THE CURL OPTIONS - SEE http://php.net/manual/en/function.curl-setopt.php
    curl_setopt( $curl, CURLOPT_URL,            $url  );
    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'  );
    curl_setopt( $curl, CURLOPT_HTTPHEADER,     $header  );
    curl_setopt( $curl, CURLOPT_REFERER,        'http://www.google.com'  );
    curl_setopt( $curl, CURLOPT_ENCODING,       'gzip,deflate'  );
    curl_setopt( $curl, CURLOPT_AUTOREFERER,    TRUE  );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE  );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE  );
    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout  );

    // RUN THE CURL REQUEST AND GET THE RESULTS
    $htm = curl_exec($curl);

    // ON FAILURE HANDLE ERROR MESSAGE
    if ($htm === FALSE)
    {
        if ($error_report)
        {
            $err = curl_errno($curl);
            $inf = curl_getinfo($curl);
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            var_dump($inf);
        }
        curl_close($curl);
        return FALSE;
    }

    // ON SUCCESS RETURN XML / HTML STRING
    curl_close($curl);
    return $htm;
}


/**
 * CREATE A SHORTCODE THAT DISPLAYS THE VISITOR MAP
 * REF: http://speckyboy.com/2011/07/18/getting-started-with-wordpress-shortcodes-examples/
 */
function visitmapper_map()
{
    global $wpdb;
    global $table_name;
    $table_name = $wpdb->prefix . "visitmapper";

    $wpdb->show_errors();

    // APPROXIMATE USA SURROUNDING AREA WITH LAT,LON
	// ME ll=50.0,-65.0
	// FL ll=25.0,-80.0
	// WA ll=50.0,-130.0
	// CA ll=25.0,-125.0

	// TRANSLATED INTO LIMITS FOR THE SELECTION
	$lo_lat = '25.000';
	$hi_lat = '50.000';
	$lo_lon = '-130.000';
	$hi_lon = '-65.000';


	// GET A COUNT OF UNIQUE LOCATIONS
	$sql = "SELECT id FROM $table_name";

	// RETURNS AN ARRAY OF OBJECTS - ONE PER ROW
	$res = $wpdb->get_results( $sql );
	$num = count($res);

    // HOW MANY MARKERS CAN WE PRODUCE?  THE MOST RECENT 25 SEEMS TO FIT
    $lim = 25;
    $sql = "SELECT lat, lon FROM $table_name  WHERE  ( (lat BETWEEN $lo_lat AND $hi_lat) AND (lon BETWEEN $lo_lon AND $hi_lon) ) ORDER BY dov DESC LIMIT $lim";
	$res = $wpdb->get_results( $sql );

    // MAKE A GOOGLE STATIC MAP OBJECT
    $gsm = new VisitmapperGSM;

    // DRAW THE MAP
    $gsm->setMapType('roadmap');
    $gsm->setWidth(620);
    $gsm->setHeight(400);
    $gsm->setZoom(3);  // HAPPY VALUE FOR HIGH-OVERVIEW OF ALL OF USA

    // MAKE THE IMAGE RESPONSIVE WITH BOOTSTRAP
    $gsm->setClass('img-responsive');

    // GET THE LAT/LON PAIRS AND SET THE MARKERS
    foreach ($res as $row)
    {
    	$gsm->setMarker("$row->lat,$row->lon", 'orange', 'small', NULL);
    }

    // ECHO THE <img /> TAG INTO OUR HTML TO DRAW THE MAP
    echo "<p>We've had $num visitors from these (and other) locations</p>" . PHP_EOL;
    echo $gsm->asIMG();
    echo PHP_EOL;
    echo "<p><b>Note: This image is responsive.  Try resizing the browser viewport!</b></p>";
    echo PHP_EOL;
}

// DEFINE THE GOOGLE STATIC MAPPING CLASS
class VisitmapperGSM
{
    // THE MAP CENTER GEOCODE, ADDRESS OR LANDMARK
    protected $center;

    // MARKER DATA ARRAY
    protected $markers;
    protected $default_icon;

    // OUR VARIABLES FOR THE MAP DISPLAY
    protected $maptype;
    protected $width;
    protected $height;
    protected $zoom;
    protected $format;

    // OUR VARIABLES FOR THE GOOGLE URL AND IMAGE TAG
    protected $alt;
    protected $title;
    protected $class;
    protected $id;
    protected $usemap;
    protected $sensor;
    protected $url;
    private $img;

    // A CONSTRUCTOR TO SET THE DEFAULT VALUES
    public function __construct()
    {
        // THE URL AND IMG TAG PARAMETERS
        $this->alt    = FALSE;
        $this->class  = FALSE;
        $this->id     = FALSE;
        $this->usemap = FALSE;
        $this->sensor = FALSE;
        $this->title  = TRUE;
        $this->url    = '';
        $this->img    = '';

        // THE CENTER AND ZOOM SCALE OF THE MAP (IF OMITTED, GOOGLE WILL CALCULATE)
        $this->center  = NULL;
        $this->zoom    = NULL;

        // THE CHARACTERISTICS OF THE MAP IMAGE
        $this->maptype = 'hybrid';    // CHOOSE
        $this->maptype = 'terrain';   // AMONG
        $this->maptype = 'satellite'; // THESE
        $this->maptype = 'roadmap';   // OPTIONS
        $this->width   = '640';
        $this->height  = '640';
        $this->format  = 'png';

        // THE DEFAULT ICON
        $this->default_icon = 'http://maps.google.com/mapfiles/ms/micons/question.png';

        // AN ARRAY OF MARKER ARRAYS
        $this->clearMarkers();

    } // END CONSTRUCTOR

    // A METHOD TO CLEAR THE MARKERS
    public function clearMarkers()
    {
        $this->markers = array();
    }

    // A SETTER TO ADD MARKERS TO THE MAP
    public function setMarker($geocode, $color='blue', $size='normal', $label='X')
    {
        $this->markers[]
        = array
        ( 'color'   => $color
        , 'label'   => $label
        , 'geocode' => $geocode
        , 'size'    => $size
        , 'icon'    => FALSE
        )
        ;
    }

    // A SETTER TO ADD ICONS TO THE MAP - VIEW SOURCE HERE: http://www.visual-case.it/cgi-bin/vc/GMapsIcons.pl
    public function setIcon($geocode, $icon=FALSE)
    {
        if (!$icon) $icon = $this->default_icon;
        $this->markers[]
        = array
        ( 'color'   => FALSE
        , 'label'   => FALSE
        , 'geocode' => $geocode
        , 'icon'    => $icon
        )
        ;
    }

    // A SETTER TO OVERRIDE EACH OF THE DEFAULT VALUES
    public function setCenter($geocode=NULL)
    {
        $this->center = $geocode;
    }
    public function setMaptype($x)
    {
        $this->maptype = $x;
    }
    public function setFormat($x)
    {
        $this->format = $x;
    }
    public function setWidth($x)
    {
        $this->width = $x;
    }
    public function setHeight($x)
    {
        $this->height = $x;
    }
    public function setZoom($x=NULL)
    {
        $this->zoom = $x;
    }
    public function setAlt($x=FALSE)
    {
        $this->alt = $x;
    }
    public function setTitle($x=TRUE)
    {
        $this->title = $x;
    }
    public function setClass($x=FALSE)
    {
        $this->class = $x;
    }
    public function setId($x=FALSE)
    {
        $this->id = $x;
    }
    public function setUsemap($x=FALSE)
    {
        $this->usemap = $x;
    }
    public function setSensor($x=FALSE)
    {
        $this->sensor = $x;
    }

    // A METHOD TO PREPARE AND RETRIEVE THE MAPPING URL
    public function asURL()
    {
        $s = 'false'; // SEE http://code.google.com/apis/maps/documentation/staticmaps/#Sensor
        if ($this->sensor) $s = 'true';

        // IF ICONS OR MARKERS ARE ON THE MAP, 'IMPLODE' THE DATA INTO THE URL
        $marker_string = '';
        foreach ($this->markers as $marker)
        {
            // PROCESS FOR CUSTOM ICONS
            if ($marker['icon'])
            {
                $marker_string
                = $marker_string
                . '&markers='
                . 'icon:'
                . urlencode($marker['icon'])
                . '|'
                . $marker['geocode']
                ;
                continue;
            }
            // PROCESS FOR STANDARD MARKERS
            $marker_string
            = $marker_string
            . '&markers='
            . 'color:'
            . $marker['color']
            . '|'
            . 'label:'
            . $marker['label']
            . '|'
            . 'size:'
            . $marker['size']
            . '|'
            . $marker['geocode']
            ;
        }

        // SET CENTER AND ZOOM, IF PRESENT
        $c = '';
        if ($this->center) $c = "&center=$this->center";
        $z = '';
        if ($this->zoom)   $z = "&zoom=$this->zoom";

        // MAKE THE URL
        $this->url
        = "http://maps.google.com/maps/api/staticmap?sensor=$s"
        . $c
        . $z
        . "&size=$this->width" . 'x' . "$this->height"
        . "&format=$this->format"
        . "&maptype=$this->maptype"
        . "$marker_string"
        ;
        return $this->url;
    }

    // A METHOD TO PREPARE AND RETRIEVE THE HTML IMAGE TAG
    public function asIMG()
    {
        // GET THE URL
        if (!$this->url) $this->url = $this->asURL();

        // GET THE ALT TEXT
        $a = "$this->maptype" . ' centered ' . "$this->center";
        if ($this->alt !== FALSE) $a = $this->alt;

        // REQUIRED FIELDS
        $this->img = '<img src="' . $this->url . '" alt="' . $a . '"';

        // OPTIONAL FIELDS - PROVIDE A DEFAULT TITLE
        $t = "$this->maptype" . ' centered ' . "$this->center";
        if     ($this->title  === TRUE ) { $this->img .= ' title="' . $t .           '"'; }
        elseif ($this->title !== FALSE)  { $this->img .= ' title="' . $this->title . '"'; }

        // OPTIONAL FIELDS MAY BE OMITTED
        if ($this->class  !== FALSE) { $this->img .= ' class="'  . $this->class  . '"'; }
        if ($this->id     !== FALSE) { $this->img .= ' id="'     . $this->id     . '"'; }
        if ($this->usemap !== FALSE) { $this->img .= ' usemap="' . $this->usemap . '"'; }

        // CLOSE THE IMAGE TAG AND CLEAR THE CONSUMED URL
        $this->img .= ' />';
        $this->url = FALSE;
        return $this->img;
    }
} // END CLASS

add_shortcode('visitmap', 'visitmapper_map');

Open in new window

0
 
LVL 70

Accepted Solution

by:
Jason C. Levine earned 250 total points
ID: 39863876
1) Is this a standalone function or part of some class. Im not a php programmer

It's a custom function defined by WordPress.  You need to call the WordPress core before using it in any script outside of WordPress:

require_once("/path/to/wordpress/wp-load.php");

Open in new window


Will load the core.

2) It uses global $wpdb and then uses this object through the function e,g, $wpdb->insert_id;
If i wanted to connect to a different wordpress database could i do this $wpdb= new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST) inside the wp_insert_post function.

Not inside.  You would need to run:

$wpdb_newdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

And then pass $wpdb_newdb to the other functions.
0
 

Author Closing Comment

by:andieje
ID: 39897092
Ray - youre a genius :)
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The purpose of this video is to demonstrate how to exclude a particular blog category from the main blog page. This is can be used when a category already has its own tab, or you simply want certain types of posts not to show up on the main blog. …
The is a quite short video tutorial. In this video, I'm going to show you how to create self-host WordPress blog with free hosting service.

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question