LoginSignup
11
8

More than 5 years have passed since last update.

WordPressのWP REST API v2でカテゴリ名を取得する

Posted at

前提

WP REST API v2のインストールしておきます
WP REST API v2ではカテゴリーのIDは取得できますが、Nameが取得できないため、下記を追加し、カテゴリーのNameがjsonで返ってくるようにします。

追加箇所

wp-content/plugins/rest-api/plugin.php

add_action( 'rest_api_init', 'register_rest_category_name'); 

if ( ! function_exists( 'register_rest_category_name' )) {
    function register_rest_category_name() {
        register_rest_field( 'post', 'category_name',
        array(
            'get_callback' => 'get_category_name'
        ));
    }
    function get_category_name( $object ) {
        $category = get_the_category($object[ 'id' ]);
        return $category[0]->cat_name;
    }
}

下記を参考にさせていただきました。ありがとうございました。

11
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
8