[英]WP REST API Update post meta using curl
I want to update post meta using curl from bash.我想使用 bash 中的 curl 更新 post meta。
The authorization is working fine with the Basic Authentication and I am able to update the post meta with a predefined string in the register_rest_field function.授权与基本身份验证一起工作正常,我能够使用 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}'
This is the curl command being used.这是正在使用的 curl 命令。 The REST API function that is being called is:正在调用的 REST API 函数是:
register_rest_field( 'custompost', 'post-meta-fields', array(
'get_callback' => function ( $data ) {
return update_post_meta(53,'website_name',$data->score);
}
)
);
I am not able to get the $data object and get the score property that is being passed in the curl command.我无法获取 $data 对象并获取在 curl 命令中传递的 score 属性。
How to get the score property which is being passed as json data in the curl command?如何获取在 curl 命令中作为 json 数据传递的 score 属性?
As per the docs Using register_rest_field 根据docs using register_rest_field
The register_rest_field function is the most flexible way to add fields to REST API response objects. register_rest_field函数是将字段添加到REST API响应对象的最灵活的方法。 It accepts three parameters: 它接受三个参数:
in your case
$data
would be an array, if not then try below code structure for Modifying Responses 在您的情况下$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.