How to display top 20 tags that are included in posts of current term of each taxonomy, excluding tags taxonomy
How to display top 20 tags that are included in posts of current term of each taxonomy, excluding tags taxonomy
I want to display tags in each taxonomy along with each tag total post counts and ordered by number of post in each tag.
If I have category term "Sports" I want to show all the tags with post counts included in posts of sports category like cricket(50), football(40), badminton(5)
As I know I've to retrieve all posts from current term which is quite simple i can do by
$args = array(
'tax_query' => array(
array(
'taxonomy' => $term->taxonomy,
'field' => 'slug',
'terms' => $term->slug,
),
),
'fields' => 'ids', // Just return post IDs
);
$query = new WP_Query($args);
and then I've to get every post tags that could be done by:
foreach ($query->posts as $post_id) {
$post_tags = get_the_tags($post_id); // Get tags for each post
if ($post_tags) {
foreach ($post_tags as $tag) {
$tags[$tag->term_id] = $tag->name; // Add tag IDs and names to array
}
}
}
What i want to do is to calculate how many posts are in each tag and then sort by total posts in tag and return only 20 tags also as much optimized as possible
I hope this is what you required
function display_tags(){
if (is_tag()) return; // Return if term is Tag
$current_term_id = get_queried_object_id(); // Get the current term ID
// fetch post IDs within the current term and their tag counts
$query_args = array(
'posts_per_page' => -1, // get all posts
'tax_query' => array(
array(
'taxonomy' => get_term($current_term_id)->taxonomy, // current taxonomy
'field' => 'term_id',
'terms' => $current_term_id,
),
),
'fields' => 'ids', // Fetch only post IDs
'post_status' => 'publish', // get only published posts
'update_post_meta_cache' => false, // Optimize by avoiding unnecessary meta retrieval
'update_term_meta_cache' => false, // same here
);
$posts_and_tags = get_posts($query_args);
// organize tags and their post counts efficiently
$tag_counts = array();
foreach ($posts_and_tags as $post_id) {
$post_tags = wp_get_post_tags($post_id, array('fields' => 'ids')); // fetch only tag IDs
foreach ($post_tags as $tag_id) {
$tag_counts[$tag_id] = isset($tag_counts[$tag_id]) ? $tag_counts[$tag_id] + 1 : 1;
}
}
// sort tags by their total posts in descending order
arsort($tag_counts);
// extract top 20 tags as an array
$top_tags = array_slice($tag_counts, 0, 20, true);
// access and return the sorted tags
$data = '';
foreach ($top_tags as $tag_id => $count) {
$data .= '<a href="' . get_tag_link($tag_id) . '" class="tags_with_count">' . get_term($tag_id)->name . ' (' . $count . ')</a>';
}
return $data;
}
January 23, 2024
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand
January 23, 2024