【问题标题】:WP REST API Update post meta using curlWP REST API 使用 curl 更新发布元数据
【发布时间】:2018-07-25 00:32:36
【问题描述】:

我想使用 bash 中的 curl 更新帖子元数据。

基本身份验证的授权工作正常,我可以使用 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 属性?

【问题讨论】:

    标签: php wordpress curl


    【解决方案1】:

    根据文档使用register_rest_field

    register_rest_field 函数是向 REST API 响应对象添加字段的最灵活方法。它接受三个参数:

    1. $object_type:对象的名称,可以是字符串,也可以是数组 为其注册字段的对象的名称。这 可能是核心类型,如“post”、“terms”、“meta”、“user”或 “comment”,但也可以是自定义帖子类型的字符串名称。
    2. $attribute:字段的名称。该名称将用于定义 响应对象中的键。
    3. $args:一个数组,其中的键定义了回调函数,用于 检索字段的值('get_callback'),以更新 字段的值('update_callback'),并定义其模式 (“模式”)。

    在您的情况下,$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'
            ),
        ) );
    } );
    

    【讨论】:

      【解决方案2】:
      add_action("rest_insert_white-paper", function (\WP_Post $post, $request, $creating) { $metas = $request->get_param("meta"); if (is_array($metas)) { foreach ($metas 作为 $name => $value) { update_post_meta($post->ID, $name, $value); } } }, 10, 3);

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      • 2013-09-09
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      相关资源
      最近更新 更多