如何使用REST API更新自定义元字段?

时间:2018-07-16 作者:user1147636

我使用rest api获得自定义元字段,但无法创建或更新。

我不是一个程序员,我在不同的网站上尝试了不同的解决方案,但都不起作用。我使用了postman,新的post创建是可以的,但没有创建自定义元字段。

示例:

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( \'job_listing\', \'post-meta-fields\', array(
           \'get_callback\'    => \'get_post_meta_for_api\',
           \'update_callback\' => \'update_post_meta_for_api\',
           \'schema\'          => null,
        )
    );
}

function get_post_meta_for_api( $object, $meta_value ) {
    //get the id of the post object array
    $post_id = $object[\'id\'];
    $meta = get_post_meta( $post_id );
    if ( isset( $meta[\'_date-start\' ] ) && isset( $meta[\'_date-start\' ][0] ) ) {
        //return the post meta
        return $meta[\'_date-start\' ][0];
    } else {
        update_post_meta( $meta, \'_date-start\', $meta_value ,true );
    }

    // meta not found
    return false;
}

1 个回复
最合适的回答,由SO网友:user1147636 整理而成

I Resolved:

function job_listings_to_api( $args, $post_type ) {
    if ( \'job_listing\' === $post_type ) {
      $args[\'show_in_rest\'] = true;
}

return $args;
}

add_filter( \'register_post_type_args\', \'job_listings_to_api\', 10, 2 );

add_action( \'rest_api_init\', \'create_api_posts_meta_field\' );

function create_api_posts_meta_field() {

register_rest_field( \'job_listing\', \'_date-start\', array(
       \'get_callback\'    => \'get_post_meta_for_api\',
       \'update_callback\' => \'update_post_meta_for_api\',
    )
);
}

function get_post_meta_for_api( $object, $field_name, $request ) {

$post_id = $object[\'id\'];

$meta = get_post_meta( $post_id );

if ( isset( $meta[\'_date-start\' ] ) && isset( $meta[\'_date-start\' ][0] 
) ) {
    //return the post meta
    return $meta[\'_date-start\' ][0];
}

return false;
}

function update_post_meta_for_api( $value, $object, $field_name ) {

if ( ! $value ) {
    return;
}

return update_post_meta( $object->ID, $field_name, $value );
}
结束

相关推荐

Php致命错误:无法将WP_REST_RESPONSE类型的对象用作wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php中

我向WordPress添加了一个自定义端点,如下所示: add_action( \'rest_api_init\', function () { register_rest_route( \'menc/v1\', \'/crosscat/(?P[\\w-]+)/(?P[\\w-]+)\', array( \'methods\' => \'GET\', \'callback\' => \'dept_cat_api\',&#x