Skip to content

Instantly share code, notes, and snippets.

@mintindeed
Created June 24, 2012 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mintindeed/2981993 to your computer and use it in GitHub Desktop.
Save mintindeed/2981993 to your computer and use it in GitHub Desktop.
WordPress get the top X tags for a post, based on how many times the tag has been used
<?php
/**
* Helper function to get the top X tags for a post, based on how many times
* the tag has been used overall.
*
* @param int $post_id
* @param int $max_tags
* @return boolean|array
*/
function pmc_get_top_tags( $post_id, $max_tags = 3 ) {
$post_id = absint( $post_id );
$max_tags = absint( $max_tags );
// Sanity check
if ( $post_id < 1 || $max_tags < 1 ) {
return false;
}
$cache_key = 'top_tags' . '_' . $post_id . '_' . $max_tags;
$cache_data = wp_cache_get( $cache_key );
if ( $cache_data ) {
return $cache_data;
}
$top_tags = wp_get_object_terms(
$post_id,
'post_tag',
array(
'orderby' => 'count',
'order' => 'DESC',
)
);
if ( ! $top_tags || is_wp_error( $top_tags ) ) {
return false;
}
// We only want to show the top $max_tags tags by count, so
// if there are more $max_tags limit to $max_tags. If there are
// fewer that's OK.
$tags_count = min( $max_tags, count($top_tags) );
$cache_data = array();
for ( $i = 0; $i < $tags_count; $i++ ) {
$cache_data[] = $top_tags[$i];
}
wp_cache_set( $cache_key, $cache_data );
return $cache_data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment