Introducing the power of “get_” alternatives of the template tags of the Loop

Hire a WordPress Expert on Codeable
Updated On: June 23rd, 2020 6 Comments

The problem with the_category() function is, it outputs all the categories of a post. As you can see in the above image, one of the posts is assigned to three categories and the layout is getting disturbed. 

Also, the designer from the client side prefers to showcase only one category in the index, So, we should output only one category.

To achieve this we have to go with the get_the_category() function.

The only difference between both the functions is, while the_category() function directly outputs the categories with hyperlinks, the get_the_category() function returns a PHP array with the categories instead of outputting them.

So, with the help of get_the_category() function, we should be able to output just a single category even if the post is assigned to multiple categories.

Go back to the index.php file and replace the following line of code:


<div class="posted-in">
    <span><?php _e( 'Posted In', 'nd_dosth' ); ?></span>
    <span><?php the_category( ', ' ); ?></span>
</div>

With this code:


<?php $categories = get_the_category(); ?>
<?php if ( ! empty( $categories ) ) : ?>
    <div class="posted-in">
        <span><?php _e( 'Posted In', 'nd_dosth' ); ?></span>
        <a href="<?php echo get_category_link( $categories[0]->term_id ); ?>"> 
            <?php echo $categories[0]->name; ?>
        </a>
    </div>
<?php endif; ?>

Now let’s break it down.

We are getting the categories in the form of an array using the get_the_category() function and saving it to a variable called $categories.

Then we are checking if there any categories assigned to a particular blog post. If our check turns true, Inside the IF condition, we are building the hyperlink for the first category from the $categories array by leaving out others.

Here is the output in the browser:

Did you see that? Our new code is just outputting a single category with hyperlink. 

If you understood the above code, feel free to skip the rest of the lesson. 

If not, let me elaborate on it. 

The variable $categories is an array and every item inside this array is an individual category with a bunch of information.

If we var_dump the $categories variable now, we will see the following output:

The blog post on the left is assigned to three categories, so the $categories has three items in the array. 

array(3) { 
    //First Item
    [0]=> object(WP_Term)#1266 (16) { 
        ["term_id"]=> int(5) 
        ["name"]=> string(6) "Advice" 
        ["slug"]=> string(6) "advice" 
        ["term_group"]=> int(0) 
        ["term_taxonomy_id"]=> int(5) 
        ["taxonomy"]=> string(8) "category" 
        ["description"]=> string(0) "" 
        ["parent"]=> int(0) 
        ["count"]=> int(6) 
        ["filter"]=> string(3) "raw" 
        ["cat_ID"]=> int(5) 
        ["category_count"]=> int(6) 
        ["category_description"]=> string(0) "" 
        ["cat_name"]=> string(6) "Advice" 
        ["category_nicename"]=> string(6) "advice" 
        ["category_parent"]=> int(0) 
    } 
    //Second Item
    [1]=> object(WP_Term)#1262 (16) { 
        ["term_id"]=> int(8) 
        ["name"]=> string(13) "Career Choice" 
        ["slug"]=> string(13) "career-choice" 
        ["term_group"]=> int(0) 
        ["term_taxonomy_id"]=> int(8) 
        ["taxonomy"]=> string(8) "category" 
        ["description"]=> string(0) "" 
        ["parent"]=> int(0) ["count"]=> int(1) 
        ["filter"]=> string(3) "raw" 
        ["cat_ID"]=> int(8) 
        ["category_count"]=> int(1) 
        ["category_description"]=> string(0) "" 
        ["cat_name"]=> string(13) "Career Choice" 
        ["category_nicename"]=> string(13) "career-choice" 
        ["category_parent"]=> int(0) 
    } 
    // Third Item
    [2]=> object(WP_Term)#1261 (16) { 
        ["term_id"]=> int(9) 
        ["name"]=> string(17) "Giving Some Space" 
        ["slug"]=> string(17) "giving-some-space" 
        ["term_group"]=> int(0) 
        ["term_taxonomy_id"]=> int(9) 
        ["taxonomy"]=> string(8) "category" 
        ["description"]=> string(0) "" 
        ["parent"]=> int(0) ["count"]=> int(1) 
        ["filter"]=> string(3) "raw" 
        ["cat_ID"]=> int(9) ["category_count"]=> int(1) 
        ["category_description"]=> string(0) "" 
        ["cat_name"]=> string(17) "Giving Some Space" 
        ["category_nicename"]=> string(17) "giving-some-space" 
        ["category_parent"]=> int(0) 
    } 
}

As you can see in the var_dump information, for every category in the array, WordPress is giving us access to a bunch of information in the form of a PHP object.

But for the problem at hand, we only need two pieces of information about an individual category object.

1) Term ID: From a coding standpoint, WordPress internally calls individual categories like “advice” as a term. And every term will have an ID.

Basically, if we have the ID of a term, we can get its permalink and other important information from the database. 

2) Name: Name is nothing but the name of the category like “advice”

Also, because we are interested in outputting only one category from the above $categories array, inside the IF condition, we are accessing the first category of the array via:

$categories[0]

That means, we are outputting the hyperlink of “advice” category from the above array:

So, inside the IF condition, The first thing we are doing is getting the URL of the first category( advice ) like this:

<a href="<?php echo get_category_link( $categories[0]->term_id ); ?>"> 
   <?php echo $categories[0]->name; ?>
</a>

The get_category_link() function does what it says. It will get the permalink of a particular category when the ID of that category is provided.

And we are accessing the ID of the category via “term_id” attribute. Remember, every item inside the array is a WordPress object. 

get_category_link( $categories[0]->term_id )

Finally, we are outputting the name of the first category by accessing the “name” attribute:

<a href="<?php echo get_category_link( $categories[0]->term_id ); ?>"> 
   <?php echo $categories[0]->name; ?>
</a>

That’s all.

This solves our problem with the categories output.

Here is the final index.php file for this lesson:


<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package Dosth
 */
get_header();
?>
<div class="content-container">
    <?php if ( is_home() ) : ?>
        <h1 class="page-title"><?php single_post_title(); ?></h1>
    <?php endif; ?>
    <div class="container">
        <div class="row">
            <div class="blog-posts col-md-8">
            <?php if ( have_posts() ): ?>
                <?php while( have_posts() ): ?>
                    <?php the_post(); ?>
                    <div class="blog-post">
                        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                        <?php if ( has_post_thumbnail() ) :
                            $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'dosth-blog-thumbnail' ); ?>
                            <div class="blog-post-thumb">
                                <a href="<?php the_permalink(); ?>"><img src="<?php echo $featured_image[0]; ?>" alt='' /></a>
                            </div>
                        <?php endif; ?>
                        <?php the_excerpt(); ?>
                        <a class="read-more-link" href="<?php the_permalink(); ?>"><?php _e( 'Read More', 'nd_dosth' ); ?></a>
                        <?php $categories = get_the_category(); ?>
                        <?php if ( ! empty( $categories ) ) : ?>
                            <div class="posted-in">
                                <span><?php _e( 'Posted In', 'nd_dosth' ); ?></span>
                                <a href="<?php echo get_category_link( $categories[0]->term_id ); ?>"> 
                                    <?php echo $categories[0]->name; ?>
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <p><?php _e( 'No Blog Posts found', 'nd_dosth' ); ?></p>
            <?php endif; ?>
            </div>
            <div id="blog-sidebar" class="col-md-4">
                
            </div>
        </div>
    </div>
</div>
<?php get_footer(); ?>

In the next lesson, we will deal with the pagination of the blog posts index.

6 Replies to “Introducing the power of “get_” alternatives of the template tags of the Loop”

  1. Rich

    Hey there, do you have a tutorial on how to create filters to view blog posts by category? Thanks

    1. Naresh Devineni

      Hi Rich, unfortunately, not at the current moment 🙁

      1. Rich

        Thanks Naresh! The closest example I’ve found is on Weichie but it seems to work with custom post types and not standard posts. It would be amazing if you can create a tutorial on how to filter standard posts by category without page-reload 🙂 love your work, thanks!

        https://weichie.com/blog/wordpress-filter-posts-with-ajax/

        1. Naresh Devineni

          Hi Rich, I will try my best to write an ultra-detailed article about the topic 🙂

          1. Rich

            Thank you 🙂

          2. Rich

            Hey Naresh, just checking in to see if you have had a chance to create a post on this? Really appreciating your series of articles on wordpress development, great stuff. Cheers!

Leave a Reply

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