wordpress rest api v2 how to list taxonomy terms?
Asked Answered
E

7

7

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 /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}}

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

Emeldaemelen answered 25/2, 2017 at 22:12 Comment(1)
use example.com/wp-json/wp/v2{your_taxonomy}Titrate
E
15

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.

Emeldaemelen answered 26/2, 2017 at 0:11 Comment(3)
THIS IS GENIUS.Colorado
This saved me!! Pure genius.Encephalo
very nice! thank you And if you want to really display all terms, you get add an array of args to get_terms - like this: php get_terms($taxonomy_name, array( 'hide_empty' => false)); Deragon
E
15

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
Encephalo answered 11/1, 2019 at 22:58 Comment(2)
This doesn't pertain to retrieving all terms within a specific taxonomy, though.Justis
This is the right answer. The accepted answer is recreating a function that already natively exists. One thing to note, if you want more than 10 results, you should add ?per_page=100 at the end of your URL. If you have more than 100 results. You need to use some pagination, i.e. to get the second page: /wp-json/wp/v2/priority-tags?per_page=100&page=2Cineaste
F
6

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.

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).

Flux answered 26/2, 2017 at 0:1 Comment(0)
W
5

TLDR

Use the flag show_in_rest when you register the taxonomy. That's all.

Details

List all available taxonomies

All default taxonomies are available via 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, e.g.

..., "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

In case your taxonomy is not listed in this taxonomy overview, you need to enable the REST endpoint when calling register_taxonomy. You can do this by adding the argument '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").


I strongly advise against creating custom REST endpoints to duplicate built-in logic.
I.e. don't do this or this

Wesle answered 17/1, 2021 at 15:40 Comment(0)
T
1

Seems some confusion for some devs even for me.

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

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

"/taxonomies" not required

Titrate answered 4/1, 2021 at 10:53 Comment(1)
This does not provide an answer to the question. Please write a comment instead.Lenticularis
C
0

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/

Crispy answered 12/10, 2018 at 17:0 Comment(0)
R
0

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

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,
            ));
        }
    }
Risteau answered 13/12, 2018 at 5:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.