WordPress.org

Ready to get started?Download WordPress

Forums

How do I show a list of tags for the current category? (2 posts)

  1. plinth
    Member
    Posted 1 year ago #

    Hi, when I visit a category page (www.myurl.com/category/global) I want to show tags in the sidebar that only apply to that category, not globally.

    I've seen code snippets that exlcude or include tags from specific categories, but I need this to be done dynamically based on the category you're currently viewing.

    Any suggestions?

  2. vtxyzzy
    Member
    Posted 1 year ago #

    I think this will do what you want:

    <?php
    /* Retrieve all tags from posts in the current category */
    
    $cat = get_query_var('cat');
    //echo "<p>CAT:$cat</p>";
    
    $sql = <<<EOSQL
    SELECT DISTINCT t.*
    FROM $wpdb->posts p
    JOIN $wpdb->term_relationships tr ON p.ID = tr.object_id
    JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id
           AND tt.taxonomy = 'post_tag')
    JOIN $wpdb->terms t ON tt.term_id = t.term_id
    WHERE
       p.ID IN (
          SELECT p2.ID
          FROM $wpdb->posts p2
          JOIN $wpdb->term_taxonomy tt2 ON (tt2.term_taxonomy_id = $cat)
          WHERE p2.post_type = 'post'
          AND p2.post_status = 'publish'
          AND p2.post_date <= NOW()
       )
    EOSQL;
    
    $terms = $wpdb->get_results($sql);
    
    // print_r($terms);
    
    echo "<br />";
    foreach ($terms as $term) {
       echo "ID:$term->term_id NAME:$term->name SLUG:$term->slug<br />";
    }
    
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic