wordpress rest api v2 如何列出分类术语? [英] wordpress rest api v2 how to list taxonomy terms?

查看:21
本文介绍了wordpress rest api v2 如何列出分类术语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 v2 的新手,我长期使用 v1,目前升级到 v2,我尝试让所有术语都属于特定的自定义分类法.

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.

在 v1 中,我可以这样做以获得条款/taxonomies/location_category/terms

In v1 i can do this to get terms /taxonomies/location_category/terms

但在 v2 中我尝试/分类法/术语它返回 json 错误 "code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}

but in v2 i try /taxonomies/terms it return json error "code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status" :404}}

如果只是/taxonomies/location_category/它没有显示任何属于分类法的术语.

if just /taxonomies/location_category/ it didn't show anything terms belong to taxonomy.

我在谷歌上搜索了几个小时没有显示任何结果,任何人都可以帮忙,谢谢

i search the question on google for few hours didn't show any result, anyone can help please, thank you

推荐答案

最后在这里写自定义代码

end out to write the custom code here

在functions.php中添加blow代码

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;
});

并输入网址 http://youdomain.com/wp-json/wp/v2/all-terms?term=you_taxonomy

so term = you_taxonomy,将得到属于 job_category 的词条.

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

这篇关于wordpress rest api v2 如何列出分类术语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆