0

I'm looking to display a list of the top 5 most used tags within a category over 30 days and the top of category.php I found a post that got me almost there but I don't know how filter it by category. Here is what I have:

global $wpdb;
$term_ids = $wpdb->get_col("
SELECT term_id , count(*) cont FROM $wpdb->term_taxonomy
INNER JOIN $wpdb->term_relationships ON $wpdb-  >term_taxonomy.term_taxonomy_id=$wpdb->term_relationships.term_taxonomy_id
INNER JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->term_relationships.object_id
WHERE DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= $wpdb->posts.post_date AND  $wpdb->term_taxonomy.taxonomy='post_tag'
GROUP BY term_id
ORDER BY cont DESC
LIMIT 5
");    
if ( count( $term_ids ) > 0 ) {
$tags = get_tags( array(
    'orderby' => 'count',
    'order'   => 'DESC',
    'number'  => 5,
    'include' => $term_ids,
) );
foreach ( (array) $tags as $tag ) {
    echo '<li><a href="' . get_tag_link ($tag->term_id) . '" rel="tag">' . 
        $tag->name . '</a></li>';
}
}
2
  • Could you clarify a bit "most used" ? As in among posts created within last 30 days with particular category?
    – Rarst
    Sep 12, 2016 at 17:35
  • I mean tags with the highest count with a specific category. Sep 13, 2016 at 17:51

1 Answer 1

1

I ended up doing this using wp_tag_cloud.

global $post;
//Tag Cloud
$cats = wp_get_post_categories( $post->ID );
$args = array(
    'category__in'          => $cats, 
    'showposts'             => -1
);
$custom_query = new WP_Query($args );
if ($custom_query->have_posts()) :
while ($custom_query->have_posts()) : $custom_query->the_post();
    $posttags = get_the_tags();
    if ($posttags) {
        foreach($posttags as $tag) {
            $all_tags[] = $tag->term_id;
        }
    }
endwhile;
endif;

$tags_arr = array_unique($all_tags);
$tags_str = implode(",", $tags_arr);

$args = array(
'smallest'  => 18,
'largest'   => 18,
'unit'      => 'px',
'number'    => 10,
'orderby'   => 'count',
'order'     => 'DESC',
'format'    => 'flat',
'include'   => $tags_str
);
echo '<div class="tag-top"><h4>Popular Tags within: ';
single_cat_title();
echo '</h4>';
wp_tag_cloud($args);
echo '</div>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.