簡體   English   中英

WP REST API 使用 curl 更新帖子元數據

[英]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響應對象的最靈活的方法。 它接受三個參數:

  1. $ object_type:對象的名稱,作為字符串,或者是為其注冊字段的對象的名稱數組。 這可能是一個核心類型,例如“ post”,“ terms”,“ meta”,“ user”或“ comment”,但也可以是自定義帖子類型的字符串名稱。
  2. $ attribute:字段名稱。 此名稱將用於定義響應對象中的鍵。
  3. $ args:帶有鍵的數組,這些鍵定義用於獲取字段值('get_callback'),更新字段值('update_callback')以及定義其模式('schema')的回調函數。

在您的情況下$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM