danial dezfooli
danial dezfooli

Reputation: 818

How to Get all terms by post type

I need to get all items in a custom taxonomy in custom post type

here is my try:

function gat_all_terms($taxonomy){

$terms = get_terms( $taxonomy, 'orderby=count&hide_empty=0' );
$count = count($terms);
$out ='';
if ( $count > 0 ){
 foreach ( $terms as $term ) {
   $out .= "<li class='item'> <a href='#'>" . $term->name . "</a></li>";

 }
}
return $out;
}

But i cant detect for a custom post type.

Upvotes: 1

Views: 2409

Answers (1)

Tim Sheehan
Tim Sheehan

Reputation: 4014

If you're trying to get the terms of a custom post type you can check out the answer here:

https://wordpress.stackexchange.com/questions/14331/get-terms-by-taxonomy-and-post-type

static public function get_terms_by_post_type( $taxonomies, $post_types ) {

    global $wpdb;

    $query = $wpdb->prepare(
        "SELECT t.*, COUNT(*) from $wpdb->terms AS t
        INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
        INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id
        INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
        WHERE p.post_type IN('%s') AND tt.taxonomy IN('%s')
        GROUP BY t.term_id",
        join( "', '", $post_types ),
        join( "', '", $taxonomies )
    );

    $results = $wpdb->get_results( $query );

    return $results;

}

Which you could convert to something simpler like:

function get_terms_by_post_type( $taxonomy, $post_type ) {

    global $wpdb;

    $query = $wpdb->prepare(
        "SELECT t.*, COUNT(*) from $wpdb->terms AS t
        INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
        INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id
        INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
        WHERE p.post_type IN('%s') AND tt.taxonomy IN('%s')
        GROUP BY t.term_id",
        $post_type,
        $taxonomy
    );

    $results = $wpdb->get_results( $query );

    return $results;

}

get_terms_by_post_type( 'taxonomy', 'type' );

Upvotes: 3

Related Questions