[英]WP REST API Update post meta using curl
我想使用 bash 中的 curl 更新 post meta。
授權與基本身份驗證一起工作正常,我能夠使用 register_rest_field 函數中的預定義字符串更新帖子元數據。
curl -X POST http://127.0.0.1/exampleporject/wp-json/wp/v2/custompost/53 -H 'content-type: application/json' -d '{"score":10}'
這是正在使用的 curl 命令。 正在調用的 REST API 函數是:
register_rest_field( 'custompost', 'post-meta-fields', array(
'get_callback' => function ( $data ) {
return update_post_meta(53,'website_name',$data->score);
}
)
);
我無法獲取 $data 對象並獲取在 curl 命令中傳遞的 score 屬性。
如何獲取在 curl 命令中作為 json 數據傳遞的 score 屬性?
根據docs using register_rest_field
register_rest_field函數是將字段添加到REST API響應對象的最靈活的方法。 它接受三個參數:
在您的情況下
$data
將是一個數組,如果不是,請嘗試下面的代碼結構來修改響應
<?php
add_action( 'rest_api_init', function () {
register_rest_field( 'comment', 'karma', array(
'get_callback' => function( $comment_arr ) {
$comment_obj = get_comment( $comment_arr['id'] );
return (int) $comment_obj->comment_karma;
},
'update_callback' => function( $karma, $comment_obj ) {
$ret = wp_update_comment( array(
'comment_ID' => $comment_obj->comment_ID,
'comment_karma' => $karma
) );
if ( false === $ret ) {
return new WP_Error(
'rest_comment_karma_failed',
__( 'Failed to update comment karma.' ),
array( 'status' => 500 )
);
}
return true;
},
'schema' => array(
'description' => __( 'Comment karma.' ),
'type' => 'integer'
),
) );
} );
add_action("rest_insert_white-paper", 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); } } }, 10, 3);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.