wordpress rest api v2 how to list taxonomy terms?

后端 未结 7 1841
情歌与酒
情歌与酒 2021-02-15 11:23

i am new to v2, i use v1 for long time, currently upgrade to v2, i try to get all the terms belong to specific custom taxonomy.

In v1 i can do this to get terms /taxonom

7条回答
  •  无人及你
    2021-02-15 11:58

    end out to write the custom code here

    add blow code to functions.php

      class all_terms
    {
        public function __construct()
        {
            $version = '2';
            $namespace = 'wp/v' . $version;
            $base = 'all-terms';
            register_rest_route($namespace, '/' . $base, array(
                'methods' => 'GET',
                'callback' => array($this, 'get_all_terms'),
            ));
        }
    
        public function get_all_terms($object)
        {
            $return = array();
            // $return['categories'] = get_terms('category');
     //        $return['tags'] = get_terms('post_tag');
            // Get taxonomies
            $args = array(
                'public' => true,
                '_builtin' => false
            );
            $output = 'names'; // or objects
            $operator = 'and'; // 'and' or 'or'
            $taxonomies = get_taxonomies($args, $output, $operator);
            foreach ($taxonomies as $key => $taxonomy_name) {
                if($taxonomy_name = $_GET['term']){
                $return = get_terms($taxonomy_name);
            }
            }
            return new WP_REST_Response($return, 200);
        }
    }
    
    add_action('rest_api_init', function () {
        $all_terms = new all_terms;
    });
    

    and enter url http://youdomain.com/wp-json/wp/v2/all-terms?term=you_taxonomy

    so term = you_taxonomy, will get terms belong to job_category.

提交回复
热议问题