When using get_categories or similar, is it possible to filter results that contain certain Tags as well?

get_categories() and related functions, by default, don’t return empty categories – categories with no posts.

I thought that, since there may be some underlying code checking the post counts, is it possible to additionally filter that list to only include categories that themselves contain posts that have a certain, specific Tag associated?

Or is there a somewhat simple alternate method of getting that information?

For example, if I had some posts with a Tag of “audio”, I’d like a way to use get_categories() (or similar results) but only retrieve a list of categories that contained posts with that “audio” Tag.

I am aware that I may have to use the Tag ID directly. I’m just looking for the “best”, or most appropriate way to do this.

Thanks!

2 Answers
2

Check out my answer on how to get terms that are associated with others through the posts that they’re attached to.

In your case, you could put it into practice like so;

$category_IDs = get_terms_soft_associated( 'category', array(
    'taxonomy' => 'post_tag',
    'field'    => 'slug',
    'terms'    => 'audio'
) );

wp_list_categories( array( 'include' => $category_IDs ) );

Or for a more general-purpose approach, use a function;

/**
 * List categories for posts that have $tag.
 * 
 * @param string|int|object $tag Tag slug, ID or object
 * @param string|array $args Args to pass to {@see wp_list_categories()}
 * @return string
 */
function list_categories_with_tag( $tag, $args="" )
{   
    if ( is_object( $tag ) )
        $tag = ( int ) $tag->term_id;

    $args = wp_parse_args( $args );
    $args['include'] = get_terms_soft_associated( 'category', array(
        'taxonomy' => 'post_tag',
        'field'    => is_numeric( $tag ) ? 'term_id' : 'slug',
        'terms'    => $tag
    ) );

    return wp_list_categories( $args );
}

Leave a Comment