wordpress rest api v2 how to list taxonomy terms?

后端 未结 7 1862
情歌与酒
情歌与酒 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:56

    The accepted answer mostly worked for me. This is what I got

     'GET',
                'callback' => array($this, 'get_all_terms'),
            )); 
        }   
        public function get_all_terms($object)
        {   
            $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(array(
                        'taxonomy' => $taxonomy_name,
                        'hide_empty' => false,
                    )); 
                }   
            }   
            return new WP_REST_Response($return, 200);
        }   
    }
    add_action( 'rest_api_init', get_all_terms);
    ?>
    

    matches the docs more closely https://developer.wordpress.org/reference/functions/get_terms/

提交回复
热议问题