Sometimes you need to print one category that characterizes the post. Imagine you have a “Most popular” widget and you wish to print the category link near each post title. How would you do that? Here is a short recipe. It applies to Wordress 3.4.1 but I assume it could be applied to a wide variety of versions.
- Install the Hikari Category Permalink plugin. It adds the “Permalink” button near each category when you edit a post. Now you can define manually which category to treat as “main”
- Write a small function anywhere you wish. I usually create a plugin named after a site name that (example.com) and put all my helpers there. The function is like that:
function example_get_main_category($post_id) { // extract the category from hikari permalink plugin $category_id = get_post_meta($post_id, '_category_permalink', true); if ( $category_id ) { return get_term($category_id, 'category'); } // no main category defined, get the default one $terms = wp_get_object_terms($post_id, 'category'); if ( $terms ) { return $terms[0]; } }
Note: By default WordPress would return the category with the lowest term_taxonomy_id.
- Now you can output taxonomy link like this:
$category = example_get_main_category($r->ID); $render_category = sprintf('<a href="%s" class="category-url">%s</a>', get_term_link($category), $category->name);
That’s all.