wordpress - Passing Meta Array in WP-REST API -
i have been trying pass meta array post via front-end using wp-rest api no avail.
functions.php:
//add custom field rest api function filter_post_json( $data, $post, $context ) { $social_media = get_post_custom_values( 'social_media' ); $sm = []; if($social_media): foreach ( $social_media $key => $value ) { $sm[] = $value; } endif; $data->data['social_media'] = $sm; return $data; } add_filter( 'rest_prepare_custom-post-type', 'filter_post_json', 10, 3 ); add_action('rest_api_init', 'register_custom_meta'); function register_custom_meta() { $post_custom_fields = array( 'social_media' ); foreach ($post_custom_fields $key) { register_rest_field('custom-post-type', $key, array( 'schema' => null, 'get_callback' => 'get_meta_field', 'update_callback' => 'update_meta_field', )); } } /** * handler getting custom field data. * * @since 0.1.0 * * @param array $object object response * @param string $field_name name of field * @param wp_rest_request $request current request * * @return mixed */ function get_meta_field( $object, $field_name, $request ) { return get_post_meta( $object[ 'id' ], $field_name ); } /** * handler updating custom field data. * * @since 0.1.0 * * @param mixed $value value of field * @param object $object object response * @param string $field_name name of field * * @return bool|int */ function update_meta_field( $value, $object, $field_name ) { if ( ! $value || ! is_string( $value ) ) { return; } return update_post_meta( $object->id, $field_name, strip_tags( $value ) ); }
jquery:
var sm1 = ['hi','hello']; console.log(sm1); var data = { social_media: sm1 }; $.ajax({ method: "post", url: post_submitter.root + 'wp/v2/custom', data: data, beforesend: function ( xhr ) { xhr.setrequestheader( 'x-wp-nonce', post_submitter.nonce ); }, success : function( response ) { console.log( response ); alert( post_submitter.success ); }, fail : function( response ) { console.log( response ); alert( post_submitter.failure ); }
this json output when try insert post:
{ "id": 120, "date": "2017-04-07t09:48:39", "date_gmt": "2017-04-07t08:48:39", "author": 1, "featured_media": 0, "menu_order": 0, "template": "", "format": "standard", "social_media": [], } }
json output when view post (for brevity have kept short):
[ { "id": 116, "date": "2017-04-07t09:43:53", "date_gmt": "2017-04-07t08:43:53", "social_media": [ "facebook", "instagram" ] }]
Comments
Post a Comment