简体   繁体   English

wordpress rest api v2 如何列出分类术语?

[英]wordpress rest api v2 how to list taxonomy terms?

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.我是 v2 的新手,我长期使用 v1,目前升级到 v2,我尝试让所有术语都属于特定的自定义分类法。

In v1 i can do this to get terms /taxonomies/location_category/terms在 v1 中,我可以这样做来获取术语 /taxonomies/location_category/terms

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}}但在 v2 我尝试 /taxonomies/terms 它返回 json 错误 "code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status" :404}}

if just /taxonomies/location_category/ it didn't show anything terms belong to taxonomy.如果只是 /taxonomies/location_category/ 它没有显示任何属于分类法的术语。

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最终在这里编写自定义代码

add blow code to functions.php向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并输入网址http://youdomain.com/wp-json/wp/v2/all-terms?term=you_taxonomy

so term = you_taxonomy, will get terms belong to job_category.所以 term = you_taxonomy,将得到属于 job_category 的术语。

For custom taxonomies, be sure that you're setting the 'show_in_rest' argument to be true (default is false) in your register_taxonomy() call .对于自定义分类法,请确保在register_taxonomy()调用中将 'show_in_rest' 参数设置为 true(默认为 false)

The register_taxonomy() call is also where you can set the 'rest_base' argument (default will be the taxonomy name, /location_category/ in your example). register_taxonomy()调用也是您可以设置“rest_base”参数的地方(默认为分类名称,在您的示例中为/location_category/ )。

Taxonomy terms are simply called this way:分类术语简称为:

https://yoursite.com/wp-json/wp/v2/the-taxonomy-slug

For instance, to answer your question:例如,要回答您的问题:

https://yoursite.com/wp-json/wp/v2/location_category

From terminal:从终端:

curl -X GET -i http://www.example.com/wp-json/wp/v2/location_category

TLDR TLDR

Use the flag show_in_rest when you register the taxonomy.注册分类时使用标志show_in_rest That's all.就这样。

Details细节

List all available taxonomies列出所有可用的分类法

All default taxonomies are available via REST API.所有默认分类法都可通过 REST API 获得。 Use the following endpoint to get a list of all available taxonomies:使用以下端点获取所有可用分类法的列表:

https://exmaple.org/wp-json/wp/v2/taxonomies

It will tell you the correct endpoint for each taxonomy in the wp:items tag, eg它会告诉您wp:items标签中每个分类法的正确端点,例如

..., "wp:items":[{"href":"https://example.com/wp-json/wp/v2/categories"}], ...
..., "wp:items":[{"href":"https://example.com/wp-json/wp/v2/tags"}], ...

Adding new taxonomies to the REST endpoint向 REST 端点添加新分类法

In case your taxonomy is not listed in this taxonomy overview, you need to enable the REST endpoint when calling register_taxonomy .如果此分类法概述中未列出您的分类法,则需要在调用register_taxonomy时启用 REST 端点。 You can do this by adding the argument 'show_in_rest' => true :您可以通过添加参数'show_in_rest' => true来做到这一点:

<php
register_taxonomy( 'location_category', 'post', [
    // ...
    'show_in_rest' => true, // ← make sure you have this line in the taxonomy args!
] );

Note: If you do NOT use show_in_rest , then the taxonomy is not available in the Block Editor ("Gutenberg").注意:如果您不使用show_in_rest ,则该分类法在块编辑器(“Gutenberg”)中不可用。


I strongly advise against creating custom REST endpoints to duplicate built-in logic.我强烈建议不要创建自定义 REST 端点来复制内置逻辑。
Ie don't do this or this即不要做这个这个

The accepted answer mostly worked for me.接受的答案主要对我有用。 This is what I got这是我得到的

<?php
// your_theme/functions.php
/**
 * how to list all taxonomy terms
 */
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)
    {   
        $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/更紧密地匹配文档https://developer.wordpress.org/reference/functions/get_terms/

If anyone is reading this in the future, I ran into an issue where the default WP category was outputting a parent key of 0, 1, 2 etc for each term object, which is a problem in itself, but a bigger problem when custom taxonomies do not have this parent value on objects如果将来有人阅读本文,我会遇到一个问题,即默认 WP 类别为每个术语对象输出 0、1、2 等的父键,这本身就是一个问题,但在自定义分类法时会出现更大的问题在对象上没有这个父值

To solve this amend the ticked example with this:要解决此问题,请使用以下内容修改打勾的示例:

    foreach ($taxonomies as $key => $taxonomy_name) {
        if($taxonomy_name = $_GET['term']){
            $return = get_terms( array( 
                'taxonomy' => $taxonomy_name,
                'hide_empty' => false,
            ));
        }
    }

Seems some confusion for some devs even for me.甚至对我来说,对于某些开发人员来说似乎有些困惑。

Correct URL is https://example.com/wp-json/wp/v2/{your_taxonomy}正确的 URL 是https://example.com/wp-json/wp/v2/{your_taxonomy}

Not https://example.com/wp-json/wp/v2/taxonomies/{your_taxonomy}不是https://example.com/wp-json/wp/v2/taxonomies/{your_taxonomy}

"/taxonomies" not required “/分类法”不需要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM