Accessing Post Information Outside the Loop

Most of the post-related template tags seen in the previous chapter (the_title(), the_content(), and so on) are available only inside the Loop. So what do you do when you need to access information outside the Loop? Use global variables! WordPress has a number of globals that store information about the current state of the application: the current post or page, user, database, and more. All these variables are available to you in your own functions and theme files.

You can access post data using the $post global. Listing 7-12 shows how to display the post's tags in a single post template's sidebar, outside the Loop.

Listing 7-12. Setting up post data to use template tags outside the Loop

<div id="sidebar"> <?php setup_postdata($post); ?>

<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>

<p class="post-tags"><?php the_tags(); ?></p>

Here, you can see how important it is to make sure that you have properly reset your query after modifying your Loops. If you didn't, the information you collect outside the Loop will refer to the last post returned by your modified Loop query, not the original query! For example, let's say you listed the author's four most recent posts at the bottom of a single post archive and didn't reset the query afterward. In your sidebar (which will come after this query in the code), you then try to display related posts based on the current post's categories and tags. If you didn't reset your query, you'll get the related posts of the author's fifth most recent rather than the one currently displayed by your single archive template.

If you aren't sure whether you're inside the Loop or not, you can use the in_the_loop() conditional tag to check. If you are inside the Loop, this function will return true, as shown in Listing 7-13.

Listing 7-13. Checking whether you're inside the Loop

<p>Am I inside the Loop? <?php if (in_the_loop()) echo "yes"; else echo "no"; ?></p>

Was this article helpful?

0 0

Post a comment