向 WP REST API 加入一些自定义的内容

Posted ·501 Views·2090 Words

博客要做 前后端分离 ,用到 REST API,但默认的输出内容有些地方不能满足需求 🙂 所以需要增加一些个性化的内容。

add_action( 'rest_api_init', 'wp_rest_insert_some' ); //添加到 REST API 中

function wp_rest_insert_some(){ //注册要个性化的功能函数

    register_rest_field( 'post',
        'post_categories',
        array(
            'get_callback'    => 'wp_rest_get_categories_links', //在 posts 中展示分类&链接&ID
            'update_callback' => null,
            'schema'          => null,
        )
    );
    register_rest_field( 'post',
        'post_excerpt',
        array(
            'get_callback'    => 'wp_rest_get_plain_excerpt', //在 posts 中展示纯文本摘录
            'update_callback' => null,
            'schema'          => null,
        )
    );
    register_rest_field( 'post',
        'post_date',
        array(
            'get_callback'    => 'wp_rest_get_normal_date', //在 posts 中展示简化后的日期
            'update_callback' => null,
            'schema'          => null,
        )
    );
    register_rest_field( 'post', 
        'post_metas', 
        array(
            'get_callback' => 'get_post_meta_for_api', //在 posts 中展示一些指定的文章自定义字段
            'update_callback' => null,
            'schema' => null,
        )
    );
}

function wp_rest_get_categories_links($post){
    $post_categories = array();
    $categories = wp_get_post_terms( $post['id'], 'category', array('fields'=>'all') );

foreach ($categories as $term) {
    $term_link = get_term_link($term);
    if ( is_wp_error( $term_link ) ) {
        continue;
    }
    $post_categories[] = array('term_id'=>$term->term_id, 'name'=>$term->name, 'link'=>$term_link);
}
    return $post_categories;

}
function wp_rest_get_plain_excerpt($post){
    $excerpts = wp_trim_words(get_the_excerpt($post['id']), 90);
    return $excerpts;
}

function wp_rest_get_normal_date($post){
    $date = get_the_date( 'y-m-d',$post['id']);
    return $date;
}

function get_post_meta_for_api($post){
    $post_meta = array();
    $post_meta['views'] = get_post_meta($post['id'],'post_views_count',true);
    $post_meta['link'] = get_post_meta($post['id'],'link',true);
    $post_meta['img'] = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');
    $post_meta['title'] = get_the_title($post['id']);
    return $post_meta;
}

 

比如,你想在使用 posts 的 REST API 时也输出你的博客名称:

add_action( 'rest_api_init', 'wp_rest_insert_some' ); //注册函数加入 REST API

function wp_rest_insert_some(){ //注册函数
    register_rest_field( 'post', 
        'blog_name',  //要注册的字段名
        array(
            'get_callback' => 'get_blog_name', //注册的要实现的功能函数
            'update_callback' => null,
            'schema' => null,
        )
    );
}

function get_blog_name($post){ //要实现的功能函数
    return get_bloginfo('name');
}

将这段代码加入主题 function.php 文件即可

访问地址为 https://www.yoursite.com/wp-json/wp/v2/posts

Comments

Leave a comment to join the discussion