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

Create custom post with meta field with AJAX and the Wordpress REST API

programmeradmin0浏览0评论

I have created a custom post type and I got it to show in the REST API. I have also registered a custom field using the following code :

function slug_get_post_meta_cb( $object, $field_name, $request ) {
    return get_post_meta( $object[ 'id' ], $field_name );
}

function slug_update_post_meta_cb( $value, $object, $field_name ) {
    return update_post_meta( $object[ 'id' ], $field_name, $value );
}

add_action( 'rest_api_init', function() {
 register_rest_field( 'custom_type',
    'myfield',
    array(
       'get_callback'    => 'slug_get_post_meta_cb',
       'update_callback' => 'slug_update_post_meta_cb',
       'schema'          => array(
           'type' => 'string',
           'context' => array( 'view', 'edit' )
       ),
    )
 );

I'm using jQuery to create an ajax POST request in order to create a new custom post with the following javascript code :

jQuery.ajax( {
                    url: requete.api,
                    method: 'POST',
                    beforeSend: function ( xhr ) {
                        xhr.setRequestHeader( 'X-WP-Nonce', questionnaireScript.nonce );
                    },
                    data:{
                        title : myData.title,
                        content: myData.content,
                        status: "publish",
                        myfield: "Stop flying"
                    }
                } ).done( function ( response ) {
                    console.log( response );
                } );

The posts are created all right, by without the custom field myfield . It does show up as part of the custom post object in the response to a GET request, but as an empty array. I also tried to set it as myfield : ["Stop flying"], and as meta : {myfield: "Stop flying"}, to no avail. I am aware of the other WP function to register a meta field (register_meta). However since the documentation reads that it cannot be applied to a custom post type only I chose to use register_rest_field instead. Any idea what I'm doing wrong ?

I have created a custom post type and I got it to show in the REST API. I have also registered a custom field using the following code :

function slug_get_post_meta_cb( $object, $field_name, $request ) {
    return get_post_meta( $object[ 'id' ], $field_name );
}

function slug_update_post_meta_cb( $value, $object, $field_name ) {
    return update_post_meta( $object[ 'id' ], $field_name, $value );
}

add_action( 'rest_api_init', function() {
 register_rest_field( 'custom_type',
    'myfield',
    array(
       'get_callback'    => 'slug_get_post_meta_cb',
       'update_callback' => 'slug_update_post_meta_cb',
       'schema'          => array(
           'type' => 'string',
           'context' => array( 'view', 'edit' )
       ),
    )
 );

I'm using jQuery to create an ajax POST request in order to create a new custom post with the following javascript code :

jQuery.ajax( {
                    url: requete.api,
                    method: 'POST',
                    beforeSend: function ( xhr ) {
                        xhr.setRequestHeader( 'X-WP-Nonce', questionnaireScript.nonce );
                    },
                    data:{
                        title : myData.title,
                        content: myData.content,
                        status: "publish",
                        myfield: "Stop flying"
                    }
                } ).done( function ( response ) {
                    console.log( response );
                } );

The posts are created all right, by without the custom field myfield . It does show up as part of the custom post object in the response to a GET request, but as an empty array. I also tried to set it as myfield : ["Stop flying"], and as meta : {myfield: "Stop flying"}, to no avail. I am aware of the other WP function to register a meta field (register_meta). However since the documentation reads that it cannot be applied to a custom post type only I chose to use register_rest_field instead. Any idea what I'm doing wrong ?

Share Improve this question asked Jun 27, 2019 at 14:34 GuitarExtendedGuitarExtended 2392 silver badges10 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

I haven't tested your code, but here the $object is an object and not array:

// Here, $object is a WP_Post object.
function slug_update_post_meta_cb( $value, $object, $field_name ) {
    return update_post_meta( $object->ID, $field_name, $value );
}

And you can actually use register_meta() with a custom post type:

register_meta( 'post', 'myfield', [
    'object_subtype' => 'custom_type', // Limit to a post type.
    'type'           => 'string',
    'description'    => 'My Field',
    'single'         => true,
    'show_in_rest'   => true,
] );

Check my answer here for more details.

Try and JSON.stringify() your data as you pass it over, and send it over as that type:

// Data to pass over
obj_to_pass = {
  title : myData.title,
  content: myData.content,
  status: "publish",
  myfield: "Stop flying"
};
// Updated AJAX call
jQuery.ajax( {
  url: requete.api,
  method: 'POST',
  beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'X-WP-Nonce', questionnaireScript.nonce );
  },
  dataType : 'json',
  data: JSON.stringify(obj_to_pass)
} ).done( function ( response ) {
  console.log( response );
} );

I felt like I have had issues with it in the past. I don't have a good testing environment to test it in, so fingers crossed!

发布评论

评论列表(0)

  1. 暂无评论