Nomura Nori
Nomura Nori

Reputation: 5167

Get custom taxonomy list on custom post type in WordPress

I am using WordPress 4.7 and created custom post type and custom taxonomy for it. My custom post type is 'products' and custom taxonomy is 'type'. To get all the taxonomies of 'type', I used following code.

<?php
   $terms = get_terms( 'type' );
   foreach ( $terms as $term ) {
    echo '<p>' .$term->name. '</p>';
   }
?>

But it returned empty array so I studied hard to find answer and found hint. I have inspected the executed queries by get_terms('type') function. They executed two important queries.

First query

SELECT    t.*, tt.* FROM wp_terms AS t    INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('type') ORDER BY t.name ASC

Next query

SELECT term_id, meta_key, meta_value FROM wp_termmeta WHERE term_id IN (10,11) ORDER BY meta_id ASC

And I make sense reason why it returned empty array. The termmeta was provided since WordPress4.4 and I use WordPress4.7. Because of second query it returned empty query. But still now I can't find right function to get all custom taxonomies for my products custom post type. I will be very glad anyone let me know how to do it in WordPress4.7 I can't use lower version only for it. Thanks.

Upvotes: 0

Views: 9770

Answers (2)

user5490424
user5490424

Reputation:

Try This code

<?php
    $terms = get_terms( array(
                'taxonomy' => 'type'
            ));
    print_r($terms);

    foreach($terms as $term) {
        echo '<p>'.$term->name.'</p>';
    }
?>

You can view more detail of get_terms() at here

Upvotes: 4

janw
janw

Reputation: 6662

get_terms recommends to add an array as arguments.
In the past the first argument was a taxonomy sting. It's not anymore. This should not matter but still it's probably the best first place to start.

<?php
$terms = get_terms( array(
    'taxonomy' => 'type',
) );

Upvotes: 0

Related Questions