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

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