最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to add a custom REST field to limit data when fetching?

programmeradmin2浏览0评论

Images don't show by default in REST API so I have added a featured image url manually and this works ok .png

add_action('rest_api_init', 'register_rest_images' );
function register_rest_images(){

    register_rest_field( array('post'),
        'feature_img_url',  
        array(
            'get_callback'    => 'get_rest_featured_image',
            'update_callback' => null,
            'schema'          => null,
        )
    );

}

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

    if( $object['featured_media'] ){
        $img = wp_get_attachment_image_src( $object['featured_media'], 'thumbnail' );
        return $img[0];
    }
    return false;

}

But I can't use it here in the fields params?

 http://localhost/wp-test/wp-json/wp/v2/posts?per_page=2&_fields=title,id,feature_img_url

I get error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data but the following works just fine .png

 http://localhost/wp-test/wp-json/wp/v2/posts?per_page=2&_fields=title,id

Do I need to additionally register something? I don't see something regarding this in the official docs /

发布评论

评论列表(0)

  1. 暂无评论