get custom post type categories

From http://codex.wordpress.com:

$categories = get_categories( $args );

$args = array(
'type'                     => 'post',
'child_of'                 => 0,
'parent'                   => '',
'orderby'                  => 'name',
'order'                    => 'ASC',
'hide_empty'               => 1,
'hierarchical'             => 1,
'exclude'                  => '',
'include'                  => '',
'number'                   => '',
'taxonomy'                 => 'category',
'pad_counts'               => false 
); 

I thought that ‘type’ was the post type. But not. This is the type of category to retrieve. I’ve researched without success.

Read More

So, any idea of how to retrieve all categories assigned to all post of specific post type?

Related posts

1 comment

  1. A brute force solution that works for any post-taxonomy relationship:

    global $wpdb;
    
    // set the target relationship here
    $post_type = 'post';
    $taxonomy = 'category';
    
    $terms_ids = $wpdb->get_col( $wpdb->prepare( "
        SELECT
            tt.term_id
        FROM
            {$wpdb->term_relationships} tr,
            {$wpdb->term_taxonomy} tt,
            {$wpdb->posts} p
        WHERE 1=1
            AND tr.object_id = p.id
            AND p.post_type = '%s'
            AND p.post_status = 'publish'
            AND tr.term_taxonomy_id = tt.term_taxonomy_id
            AND tt.taxonomy ='%s'
        ", $post_type, $taxonomy ) );
    
    // here you are
    $terms = get_terms( $taxonomy, array(
        'include' => $terms_ids,
        'orderby' => 'name',
        'order' => 'ASC'
    ) );
    

Comments are closed.