WordPress Template Tags: How They Show Post Content & More

WordPress template tags are a super-important and super-valuable part of WordPress, especially for theme development. They’re also one of the things I remember spending lots of time not quite getting as I was learning WordPress.

So today we’re happy to present you with our free chapter on WordPress template tags from our full “learn WordPress development” guide, Up and Running!

The Best Way to Learn WordPress Development

Get Up and Running Today

Up and Running is our complete “learn WordPress development” course. Now in its updated and expanded Third Edition for 2018, it’s helped hundreds of happy buyers learn WordPress development the fast, smart, and thorough way.

Here’s what they have to say:

“I think anyone interested in learning WordPress development NEEDS this course. Watching the videos was like a bunch of lights being turned on.” -Jason, WordPress developer

“Other courses I’ve tried nearly always lack clear explanations for why WordPress does things a certain way, or how things work together. Up and Running does all of this, and everything is explained clearly and in easy-to-understand language.” -Caroline, WordPress freelancer

Like each chapter of Up and Running, this one starts with the “Key Takeaways” about WordPress’s post template tags.

Key Takeaways:

  • Template tags is the generic term for functions designed to work mainly inside WordPress’s PHP templates, especially inside The Loop.
  • A common pattern, true across most template tags, is that functions beginning with get_the_ will return a value for later use, while functions beginning with the_ will echo a value directly onto the page.
  • Most the_() and get_the_() functions are designed to operate inside The Loop. However, many get_the_() functions can be called outside The Loop, if given a post ID as a function parameter.

Some WordPress functions are designed to work inside page templates—the PHP files like header.php, index.php, and page.php that make up the body of any WordPress theme.

Some WordPress functions are designed to work inside page templates. These functions are called template tags.

These functions are called template tags, and they’re among WordPress’s most important and easiest-to-use functions.

Understanding the_() and get_the_() Template Tags

Template tag names often start with either the_ or get_the_, and they often either print or retrieve information related to the current post.

Template tags do all kinds of things—you can see the full list at https://codex.wordpress.org/Template_Tags—but the most important ones often do one of two things:

  1. Retrieve information related to the current post
  2. Print information related to the current post onto the page

Not all template tags do one of these things, but this chapter will only cover the ones that do.

One more thing to know: these template tags often have predictable names: they often start with either the_ or get_the_.

This pattern in naming matches a really important pattern in functionality:

In WordPress, the_() Functions echo Things, and get_() Functions return Things

This is an important pattern to get under your skin:

  1. the_() functions echo a value: they print something directly onto the page as HTML.
  2. get_() functions return a value: they give your PHP script something that it can use later.

An Example

To illustrate, let’s look more closely at two template tags: the_title() and get_the_title().

<?php /* Environment: We're INSIDE The Loop, and the current post's title is "My Favorite Post" */

/*  Using the_title() */
the_title(); // Prints out the string "My Favorite Post"
$broken_variable = the_title(); // Prints out the string "My Favorite Post"
echo $broken_variable; // Prints out nothing; $broken_variable is NULL

/* Using get_the_title() */
get_the_title(); // Doesn't accomplish anything
echo get_the_title(); // Prints out the string "My Favorite Post"
$post_title = get_the_title(); // Saves the value "My Favorite Post" to the variable $post_title
echo $post_title; // Prints out the string "My Favorite Post"

Let’s look, step by step, at the results for each of our lines of code:

the_title();

This function’s designed to print things, so that’s what happens. The HTML page will now have “My Favorite Post” on it.

$broken_variable = the_title();

Don’t do this. the_title() always prints onto the page, so you now get the string “My Favorite Post” printed straight onto your page, and you don’t successfully save that string to the $broken_variable variable.

get_the_title();

Don’t do this: it doesn’t do anything. More specifically, it does get the title, but doesn’t use it for anything. Remember, get_() functions don’t print by default.

echo get_the_title();

Gets the title, and then prints that with echo. Writing this line is exactly the same as just writing the_title().

$post_title = get_the_title();

This line doesn’t print anything, but does save the value “My Favorite Post” to the variable $post_title.

echo $post_title;

Since we previously saved the string “My Favorite Post” to $post_title, echoing that variable prints it straight onto the page.

A Second Example

Let’s look at PHP more in-context with HTML. Pretend we’re in our theme’s index.php file, and want to print each post’s excerpt onto the page. Here are some options:

/* We're INSIDE The Loop */

<div><?php get_the_excerpt(); ?></div>
<!-- Nothing echoed, so results in an empty div element -->

<div><?php the_excerpt(); ?></div>
<!-- Prints out the post's excerpt inside the div element -->

<div><?php echo get_the_excerpt(); ?></div>
<!-- Prints out the post's excerpt inside the div element -->

<div><?php echo 'Excerpt: ' . get_the_excerpt(); ?></div>
<!-- Prints out "Excerpt: " and the post's excerpt inside the div element -->

This naming relationship holds across the WordPress function library! The only real exception to keep in mind is that the_post() does something important, and doesn’t echo anything. (Remember, though: You don’t really have to understand the_post() as long as you always remember to write it into your Loop.)

Some Important the_() and get_the_() Template Tags to Know

The following functions are utterly crucial to theme development. They’re also really easy to use, so if you’re like us you’ll come to love them right away. Here they are:

  • the_title() and get_the_title(): prints or retrieves the current post’s title
  • the_permalink() and get_the_permalink(): prints or retrieves a link to the URL of the current post
  • the_content() and get_the_content(): prints or retrieves the current post’s content
  • the_excerpt() and get_the_excerpt(): prints or retrieves an excerpt of the beginning of the current post
  • the_author() and get_the_author(): prints or retrieves the public name of the current post’s author

For the full list of template tags, check out the Codex at: https://codex.wordpress.org/Template_Tags

Most the_() and get_the_() Template Tags Happen In The Loop

Some functions must be called within The Loop, and some shouldn’t be. Let’s look at the patterns there, and how template tags fit into it.

What “In the Loop” Means

Just so we’re clear, here’s what “inside The Loop” and “outside The Loop” mean. Pretend we’re looking at a PHP template in the WordPress template hierarchy, like your theme’s index.php, single.php, or home.php files:

// We're now OUTSIDE The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
	// We're now INSIDE The Loop, working on posts one-by-one; "in-The-Loop" functions go here
endwhile; endif;
// We're OUTSIDE The Loop again

Functions that Work on Individual Posts Usually Happen in The Loop

Functions that retrieve, alter, or display the properties of individual posts should generally take place inside The Loop.

Why? Because The Loop is what moves through individual posts one-by-one and does things to them. The Loop is what processes raw posts into webpages, so for functions that participate in that process in a predictable way (say, printing out each post’s title with the_title()), The Loop is the natural place to be.

A template file that makes good use of “In-the-Loop” functions might look something like this:

<?php 
// We're now OUTSIDE The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
	// We're now INSIDE The Loop
	<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><h2>
	<span class="author-name">By <?php the_author(); ?></span>
	<section><?php the_excerpt(); ?></section>
endwhile; endif;
// We're OUTSIDE The Loop again

Some “In The Loop” Functions Can Be Called Outside It, with Function Parameters

Less commonly, some functions that work with individual posts can also be called outside The Loop. If so, though, they must be given the ID of the post as a function parameter so that they know which post to act on.

This will make more sense with an example. For this example, we’re outside The Loop. That could be lots of places: in index.php but outside The Loop, in footer.php or another non-Loop template file, in functions.php, or in a PHP file in a plugin.

/* We're OUTSIDE The Loop right now */

$title_broken = get_the_title(); // Won't work! Get the title of which post?

$title_working = get_the_title( 2 ); // Will get the title of the post whose post ID is 2, if that post exists

echo $title_working; // Will print out the title of the post whose post ID is 2, if that post exists

echo get_the_title( 3 ); // Will print out the title of the post whose post ID is 3, if that post exists

See? get_the_title() can be called outside The Loop, with a function parameter (the 2 or 3 in the example above) that says which post it is whose title we want to retrieve. Many of the get_the_() template tags work similarly.

the_() Functions are Loop-Only

the_() functions are Loop-only! So the following won’t work:

/* We're OUTSIDE The Loop right now */

the_title(); // Won't work! the_title() is Loop-only

the_title( 2 ); // Won't work! the_title() is Loop-only and takes no parameters

Summary: The Loop and WordPress Template Tag Names

To repeat and summarize the above in practical terms:

  1. the_() functions assume knowledge of the current post, so they only make sense inside The Loop.
  2. Most get_the_() functions are meant primarily in The Loop. To work outside The Loop, these functions need to be given a post ID as a function argument, so that they know what post to act on.
  3. Functions that aren’t used to retrieve, alter, or display individual post properties—some get_ functions, and most other functions that don’t start with the_—shouldn’t be called in The Loop.

Final Note: Naming Inconsistencies

WordPress functions are not named perfectly consistently. Some get_() functions behave exactly like the get_the()functions described here—and match a corresponding the_() function—but are missing the_ in their function names for whatever reason. (get_permalink() is an obvious example, although mercifully get_the_permalink() was added in WordPress 3.9.)

Other get_() functions do “get” (retrieve) things, but they act nothing like the functions covered in this chapter. get_header() actually includes the entire contents of header.php, for example. Just know that things aren’t perfectly consistent, and you’ll learn the odd bits quickly.

Summary Limerick

Here’s something simple to learn:
get_the_()‘s designed to return,
And generally the_()
Prints immediately;
You’ll use each type plenty in turn.

Quiz Time!

  1. What will be the effect of running just get_the_author(); inside The Loop?
    1. The current post’s author will be printed onto the page
    2. The current post’s author will be saved into WordPress’s global state
    3. Nothing
  2. Called inside The Loop, the_title(); is equivalent to:
    1. get_the_title();
    2. echo get_the_title();
    3. return get_the_title();
  3. The following code will properly execute outside The Loop:
    1. the_content();
    2. get_the_content();
    3. get_the_content( 2 );

Answers and Explanations

  1. C. Just getting a return value has no effect if you don’t do anything with it. A would be the correct answer for a Loop that calls the_author();.
  2. B. the_title(); retrieves the current post’s title and immediately echos it; it is a kind of predefined shorthand for echo get_the_title();.
  3. C. the_() functions don’t work outside The Loop. get_the_content() doesn’t know which post to act on by default, but can run if passed a post ID (2 in this case) or a post slug as a function argument.

Image credit: Douglas R Witt


4 Responses

Comments

  • Luca R. says:

    One important thing to point out is the inconsistency in applying the filters between the_content(), the_excerpt() and the_title().

    the_content() applies the_content filter, while get_the_content() does not. So, if you want to display the content of a post outside of the loop, you may want to do this:

    In the same odd fashion, the_excerpt() applies the_excerpt filter, while get_the_excerpt() does not. It does, however, apply the get_the_excerpt filter.

    Arguably the most notable inconsistency is probably the the_title filter, which gets applied to BOTH get_the_title() AND the_title(). So, if you want the unfiltered title, you must get it directly from a post object, i.e.:


    post_title;
    ?>

    Hope this helps in understanding template tags. Good coding 🙂

    • Luca R. says:

      Uhm, code blocks are not displayed correctly. Let’s try again:

      So, if you want to display the content of a post outside of the loop, you may want to do this:


      $content = get_the_content( 1 );
      echo apply_filters( 'the_content', $content );

      If you want the unfiltered title, you must get it directly from a post object, i.e.:


      global $post;
      $title = $post->post_title;

Pingbacks

Add a Comment

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