Add post meta fields, when creating a post using WordPress’ REST API

Question

In the documentation for /posts for WordPress REST API it states that I can add a meta-field. But it doesn’t say which format that should be in.

I can find other guides showing how it should be if using Postman:

data = {
  "title": "test",
  "content": "testingfrompython",
  "status": "draft",
  "author": 1,
  "meta": {
    "location": "NYC",
    "date": "never",
    "event_url": "http: //google.com"
  },
  "featured_media": 1221
}

But how should it be setup, if I’m call the endpoint using PHP and cURL?


This here works for just creating a post:

$data = [
  'title'   => 'Test post',
  'status'  => 'draft', 
  'content' => 'Some content',
];
$data_string = json_encode( $data );

$endpoint = 'https://example.org/wp-json/wp/v2/posts';
$protocol = "POST";

$headers = [
  'Content-Type: application/json',
  'Content-Length: ' . strlen($data_string)
  'Authorization: Basic ' . base64_encode( 'MYUSERSEMAIL:APPLICATIONPASSWORD' )
];

$ch = custom_setup_curl_function( $endpoint, $protocol, $data_string, $headers );
$result = json_decode( curl_exec($ch) );

I’ve tried all kind of things:

Attempt1

$data = [
  'title'   => 'Test post',
  'status'  => 'draft', 
  'content' => 'Some content',
  'meta' => [
    'my_custom_field' => 'Testing 1234'
  ]
];

Attempt2

$data = [
  'title'   => 'Test post',
  'status'  => 'draft', 
  'content' => 'Some content',
  'meta' => [
    [
      'key' => 'my_custom_field', 
      'value' => 'Testing 1234' 
    ]
  ]
];

… And I could keep going. Every time it simply creates a post, but doesn’t add any of the meta-data to my created custom fields.

I don’t get why this is not stated in the documentation for the REST API.

0
Zeth 5 months 2020-12-28T08:10:18-05:00 0 Answers 2 views 0

Leave an answer

Browse
Browse