How to print default category of a post in WordPress

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.

  1. 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”
  2. 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.

  3. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.