wp-rest-api添加自定义字段输出

正常wp-rest-api输出的内容是不包含自定义字段的,如果想输出自定义字段的内容,可以这样解决:

1、在wordpress根目录下找到wp-includes / rest-api.php文件,

2、在文件中添加以下代码:

/**添加自定义字段输出**/

add_action( 'rest_api_init', 'create_api_posts_meta_field' );

function create_api_posts_meta_field() {

	// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
	register_rest_field( 'post', 'post-meta-fields', array(
	       'get_callback'    => 'get_post_meta_for_api',
	       'schema'          => null,
	    )
	);
}

function get_post_meta_for_api( $object ) {
	//get the id of the post object array
	$post_id = $object['id'];

	//return the post meta
 	return get_post_meta( $post_id );
}

 

问题解决!!!
参考来源:
https://wndwp.com/article/68

register_rest_field()

未经允许不得转载:WEIXING.ME » wp-rest-api添加自定义字段输出

相关文章

评论 (0)