我一直在尝试使用WP-REST API通过前端将元数组传递到帖子,但无济于事。
的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 );
}
当我尝试插入帖子时,这是JSON输出:
{
"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输出(为了简洁,我保持简短):
[
{
"id": 116,
"date": "2017-04-07T09:43:53",
"date_gmt": "2017-04-07T08:43:53",
"social_media": [
"facebook",
"instagram"
]
}]