1

I have this code that inserts a post into WordPress site using Rest API:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $row->site_url."/wp-json/wp/v2/posts");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Authorization: Bearer '.$row->token
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    "title"=>$row->title,
    "content"=>$row->content,   
    "excerpt"=>$row->excerpt,                                                                                                                               
    "status"=>'publish',
    "categories"=>(int)$row->c_wp_id
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$result_decoded = json_decode($result);
$post_id=$result_decoded->id;

I need to add meta , how do I do that?

I have tried this but it's not saving the meta:

$tst = (object)array(
    'some_key' => 'some_test_again'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $row->site_url."/wp-json/wp/v2/posts/".$row->wp_post_id);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Authorization: Bearer '.$row->token
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    "title"=>$post_array['title'],
    "content"=>$post_array['content'],  
    "excerpt"=>$post_array['excerpt'],                                                                                                                          
    "meta"=>$tst
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$result_decoded = json_decode($result);
$post_id=$result_decoded->id;
4
  • 1
    Register the meta. My answer here might also help you.
    – Sally CJ
    Apr 4 '19 at 12:59
  • Can I use the register_meta function inside my codeigniter app? I'm using the Rest Wordpress Api inside my codeigniter app, all the above code is written inside this codeigniter app @SallyCJ Apr 5 '19 at 7:47
  • Is your codeigniter app an external app that's just using the WordPress REST API? Then no. You'll have to call register_meta from a WordPress plugin.
    – Rup
    Apr 5 '19 at 13:17
  • The meta needs to be registered (and enabled in the REST API) on the WordPress website in which you're making the REST API request to. If you don't have access/control to the site, try asking the site owner/dev to register the meta.. or they might have other option for you for adding or updating post metadata via the REST API.
    – Sally CJ
    Apr 5 '19 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.