wordpress 扩展REST API

后端 2019-10-07T09:05:38 浏览:297

修改响应:使用register_rest_field将字段添加到REST API响应对象

有的时候wordpress自带的restapi无法满足我们的实际项目需求,我们需要扩展wordpress的RESTAPI。以下是片段代码以此类推用来扩展wordpress的RESTAPI

/*-----------------------------------------------------------------------------------*/
/*  获取文章含有的图片
/*-----------------------------------------------------------------------------------*/
function get_post_images(){  
    global $post;
    $content = $post->post_content;
    preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $result, PREG_PATTERN_ORDER);
    return $result[1];
} 
/*-----------------------------------------------------------------------------------*/
/*  获取特色图片
/*-----------------------------------------------------------------------------------*/
function get_rest_featured_image( $object) {
    if( $object['featured_media'] ){
        $img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' );
        return $img[0];
    }
    return false;
}

function register_rest_fields(){
    register_rest_field( array('post'),
        'fimg_url',
        array(
            'get_callback'    => 'get_rest_featured_image'
        )
    );
    register_rest_field( array('post'),
        'imagesnum',
        array(
            'get_callback'    => 'get_post_images'
        )
    );
}

add_action('rest_api_init', 'register_rest_fields' );