1

I need to programmatically create new Wordpress posts and assign custom fields to each. Using the Wordpress xmlrpc API, I can successfully add a new post, but the custom fields are not added.

Here's an excerpt of the code:

$blogid = 0;
$username = 'user';
$password = 'xyzzy1234';
$method = 'wp.newPost';
$title = "Post Title";
$pcontent = "I'm the post content.";
$categories = array('Cat 1', 'Cat 2');
$post_status = 'publish';  
$custom_fields = array('cccId' => '12345', 'cccType' => 'news');
$content = array(
                'post_type' => 'post',
                'post_status' => $post_status,
                'post_title' => $title,
                'post_content' => $pcontent,
                'terms_names' => array('category'=>$categories),
                'comment_status' => $comment_status,
                'ping_status' => $ping_status,
                'custom_fields' => $custom_fields
            );

$parameters = array($blogid, $username, $password, $content);
$response = sendRequest($method, $parameters);

function sendRequest($methodName, $parameters)  {
$request = xmlrpc_encode_request($methodName, $parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, RPC_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
$results = print_r(xmlrpc_decode($results));
curl_close($ch);
return $results;
}

1 Answer 1

4

After some experimentation, it turns out that $custom_fields needs to be specified like this:

$custom_fields = array(
                   array('key' => 'cccId', 'value' => '12345'),
                   array('key' => 'cccType', 'value' => 'news')
                 );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Couldn't find any accurate documentation for this and was bumping my head until I found this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.