I have been trying to pass a meta array to a post via front-end using WP-REST API but to no avail.

functions.php:

//Add custom field to REST API
function filter_post_json( $data, $post, $context ) {
  $social_media = get_post_custom_values( 'social_media' );

  $sm = [];
  if($social_media):
    foreach ( $social_media as $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 as $key) {
     register_rest_field('custom-post-type', $key, array(
     'schema'          => null,
     'get_callback'    => 'get_meta_field',
     'update_callback' => 'update_meta_field',
   ));
  }
}


/**
 * Handler for getting custom field data.
 *
 * @since 0.1.0
 *
 * @param array $object The object from the 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 for updating custom field data.
 *
 * @since 0.1.0
 *
 * @param mixed $value The value of the field
 * @param object $object The object from the 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 is the JSON output when I try to insert a 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 I view a post (for brevity I have kept it short):

[
{
"id": 116,
"date": "2017-04-07T09:43:53",
"date_gmt": "2017-04-07T08:43:53",
"social_media": [
"facebook",
"instagram"
]
}]

Read more here: Passing Meta Array in WP-REST API


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: