0

The site I am working on has about 4 different post categories. I need to output a list (unordered) of tags in that category so that a user can click on them and see posts in THAT category tagged with whatever they just clicked on. My problem is I'm not sure how to limit to just a certain category such as 'recipes' or 'stories'.

Here is what I have so far:

$args = array( 
        'hide_empty' => 0, 
    );

    $terms = get_terms('post_tag', $args );
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
        $count = count( $terms );
        $i = 0;
        $term_list = '<p class="my_term-archive">';
        foreach ( $terms as $term ) {
            $i++;
            $term_list .= '<a href="' . get_term_link( $term ) . '" title="' . sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $term->name ) . '">' . $term->name . '</a>';
            if ( $count != $i ) {
                $term_list .= ' &middot; ';
            }
            else {
                $term_list .= '</p>';
            }
        }
        echo $term_list;
    }

I havent changed the styling yet, but I will - but it outputs all of my tags sitewide.

I've found lots of info like this http://www.wprecipes.com/wordpress-trick-function-to-get-tags-related-to-category

But it all seems old and perhaps out of date. Isn't there a way to do it more elegantly using get_terms()?

  • there's really not an elegant way to do this, as there's no relationship between categories and tags without looking at the posts that share both. – Milo Oct 30 '15 at 19:46
  • So... you would need to query all posts with that category, loop through each one to get the tags from all of those posts, put them into an array to remove the duplicate tags. One a site with a lot of posts this query could be huge and slow down the site loading time a lot. If you really want to do it, I would suggest using $wpdb for your custom sql queries and then use transients to cache the result. – gdaniel Oct 30 '15 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.