user2984982
user2984982

Reputation: 13

Post to wordpress via php

I'm trying to post on my wordpress site using php .

I used php to fetch data from a website and stored all of them in variables .

I found the code to a few auto wordpress php posters but they are kind of complex and i'm not really sure how to use/alter them.

What the simplest way to do it via php ?

My data are like :

$topic_name = "name";

$mainimage = "url/image":

$input = "hello................." ;

$category = "cars";

$tags = ("tag1","tag2","tag3"...);

Note : I just need the basic code to login to my wordpress and post some random text via php - I'm pretty sure i can figure out how to input the category , tags etc later on.

I'm trying to use this one as it seem simple but i don;t think it works for the latest version of wordpress (3.7.1 ) -

If anyone can modify it or can share a working one , would be great .

function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8') {
    $title = htmlentities($title,ENT_NOQUOTES,$encoding);
    $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);

    $content = array(
        'title'=>$title,
        'description'=>$body,
        'mt_allow_comments'=>0,  // 1 to allow comments
        'mt_allow_pings'=>0,  // 1 to allow trackbacks
        'post_type'=>'post',
        'mt_keywords'=>$keywords,
        'categories'=>array($category)
    );
    $params = array(0,$username,$password,$content,true);
    $request = xmlrpc_encode_request('metaWeblog.newPost',$params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_URL, $rpcurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    $results = curl_exec($ch);
    curl_close($ch);
    return $results;
}

Upvotes: 0

Views: 2317

Answers (1)

Michael Hampton
Michael Hampton

Reputation: 9980

Do you really need to use XML-RPC? This is generally what you would want to do to post to a remote WordPress installation. For instance, from a completely different site, from a mobile app, etc.

It sounds like you are writing a plugin that will run within your WordPress installation. In that case you can just call wp_insert_post() directly.

A very trivial example from WordPress's wiki, which also has a complete list of parameters you can use:

// Create post object
$my_post = array(
  'post_title'    => 'My post',
  'post_content'  => 'This is my post.',
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_category' => array(8,39)
);

// Insert the post into the database
wp_insert_post( $my_post );

Upvotes: 2

Related Questions