使用WordPress的REST API创建帖子时,添加帖子元字段

时间:2020-12-28 作者:Zeth

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.

2 个回复
SO网友:cvl01

在最近的WP版本中,处理此问题的建议方法是使用register\\u meta或register\\u post\\u meta函数。

使用register\\u post\\u meta函数,可以指定要将字段分配给的post\\u类型、元键和属性数组,重要的属性是show_in_rest

add_action(\'init\', function(){

    register_post_meta(
        \'my_custom_post_type\',
        \'_custom_meta_key\',
        array(
            \'single\'       => true,
            \'type\'         => \'string\',
            \'show_in_rest\' => true,
        )
    );
});

SO网友:Zeth

我不得不补充this code 斯蒂芬·马伦(Stephen Mullen)在《StackOverflow》中写道:

add_action( "rest_insert_user_question", function ( \\WP_Post $post, $request, $creating ) 
{
    $metas = $request->get_param( "meta" );
    if( is_array( $metas ) ) {
        foreach( $metas as $name => $value ) {
            // update_post_meta( $post->ID, $name, $value );
            update_field( $name, $value, $post->ID );
        }
    }
}, 10, 3 );
然后我可以这样调用端点:

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