最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp api - Update Custom Post Type Metadata Wp Rest API

programmeradmin2浏览0评论

I am trying to update a custom post type metadata on the front end using JS and the WP Rest API.

The object key is wishlist_array under metadata

Here is how JSON response from /wp-json/wp/v2/oha_wishlist (my custom post) looks:

{
"id": 1248,
.
.
.
"metadata": {
    "wishlist_array": [
        ""
     ],
.
.
.

On php I set the register_rest_field() function as follow:

register_rest_field('oha_wishlist', 'metadata', array(
    'get_callback' => function ($data) {

        return get_post_meta($data['id'], '', '');
    },
     'update_callback' => function ($data) {
         // Don't understand how to use the arguments here
         // How can I print or log the $data content??
         return update_field($??, $??, $??);
     },

And finally my fetch() function where I connect to the API. It returns no error and if I try to update the title, for instance, it works well. Only doesn't when trying to update the metadata.

fetch("/wp-json/wp/v2/oha_wishlist/1248", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-WP-Nonce": phpVarObj.nonce
        },
        body: JSON.stringify({ metadata: { wishlist_array: "add this" } })
      })
        .then(function(response) {
          return response.json();
        })
        .then(function(wishlistPosts) {
          console.log(wishlistPosts);
        });

I am trying to update a custom post type metadata on the front end using JS and the WP Rest API.

The object key is wishlist_array under metadata

Here is how JSON response from http://ohalocal.local/wp-json/wp/v2/oha_wishlist (my custom post) looks:

{
"id": 1248,
.
.
.
"metadata": {
    "wishlist_array": [
        ""
     ],
.
.
.

On php I set the register_rest_field() function as follow:

register_rest_field('oha_wishlist', 'metadata', array(
    'get_callback' => function ($data) {

        return get_post_meta($data['id'], '', '');
    },
     'update_callback' => function ($data) {
         // Don't understand how to use the arguments here
         // How can I print or log the $data content??
         return update_field($??, $??, $??);
     },

And finally my fetch() function where I connect to the API. It returns no error and if I try to update the title, for instance, it works well. Only doesn't when trying to update the metadata.

fetch("http://ohalocal.local/wp-json/wp/v2/oha_wishlist/1248", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-WP-Nonce": phpVarObj.nonce
        },
        body: JSON.stringify({ metadata: { wishlist_array: "add this" } })
      })
        .then(function(response) {
          return response.json();
        })
        .then(function(wishlistPosts) {
          console.log(wishlistPosts);
        });
Share Improve this question asked Jun 15, 2019 at 14:52 stemonstemon 1551 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

If you're supplying the request data/body like so, which is an array of metadata:

{ metadata: { wishlist_array: "add this", foo: "bar baz" } }

and you want to update only the wishlist_array metadata, then you could do:

// In your case, $field_value is the `metadata` value and $data is a WP_Post object.
'update_callback' => function( $field_value, $data ){
    if ( is_array( $field_value ) && isset( $field_value['wishlist_array'] ) ) {
        update_post_meta( $data->ID, 'wishlist_array', $field_value['wishlist_array'] );
        return true;
    }
}

Or if you want to update all metadata (or all fields supplied in that metadata array), then this would do it:

// In your case, $field_value is the `metadata` value and $data is a WP_Post object.
'update_callback' => function( $field_value, $data ){
    if ( is_array( $field_value ) ) {
        foreach ( $field_value as $key => $value ) {
            update_post_meta( $data->ID, $key, $value );
        }
        return true;
    }
}

And regarding this question: "// How can I print or log the $data content??", you could do var_dump( $data ); and check the PHP error logs — or wp-content/debug.log if it is enabled.

Some Notes

  1. In the update_callback function, the $field_value is the value of the metadata parameter; whereas the $data is the data object — this is equivalent to the $data in the get_callback function, except that in the update_callback function, the $data is not an array.

  2. You may also want to check this sample code on the REST API handbook.

  3. The examples above are basic examples and as stated on the REST API handbook, carefully consider what permissions checks or error handling may be required for your specific field.

  4. With update_field() (ACF), you could also use $data->ID as the third parameter passed to update_field().

发布评论

评论列表(0)

  1. 暂无评论