WordPress: Customizing Content Display

Exclusive offer: get 50% off this eBook here
WordPress 3 Cookbook

WordPress 3 Cookbook — Save 50%

Over 100 recipes to help you enhance your WordPress site! with this book and ebook

$23.99    $12.00
by Ric Shreves | December 2011 | Open Source WordPress

What is the WordPress loop? The loop is a group of PHP instructions that retrieve posts from the database of your WordPress site and then displays them on the page. You can find the WordPress loop inside your themes, for example, inside index.php, single.php, or page. php. Any HTML or PHP code placed between the beginning of the loop and the end will be used for each post.

In this article by Ric Shreves, author of WordPress 3 Cookbook, we will cover:

  • How to work with the WordPress loop
  • How you can retrieve posts from a specific category
  • How to control how many posts you display
  • Retrieving posts by date
  • Showing only those posts published today
  • How to show posts published exactly one year ago
  • How to set up and use multiple loops

(For more resources on WordPress, see here.)

At its most basic, a simple implementation of the loop could work like this:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endwhile; else: ?>
<p>Sorry, no posts matched your criteria.'</p>
<?php endif; ?>

In the real world, however, the WordPress loop is rarely that simple. This is one of those concepts best explained by referring to a real world example, so open up the index.php file of your system's TwentyEleven theme. Look for the following lines of code:

<?php if ( have_posts() ) : ?>
<?php twentyeleven_content_nav( 'nav-above' ); ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format()
); ?>
<?php endwhile; ?>
<?php twentyeleven_content_nav( 'nav-below' ); ?>
<?php else : ?>
<article id="post-0" class="post no-results not-found">
<header class="entry-header">
<h1 class="entry-title"><?php _e( 'Nothing Found',
'twentyeleven' ); ?></h1>
</header><!-- .entry-header -->
<div class="entry-content">
3
<p><?php _e( 'Apologies, but no results were found
for the requested archive. Perhaps searching will help
find a related post.', 'twentyeleven' ); ?></p>
<?php get_search_form(); ?>
</div><!-- .entry-content -->
</article><!-- #post-0 -->
<?php endif; ?>

Most of the extra stuff seen in the loop from TwentyEleven is there to add in additional page elements, including content navigation; there's also some code to control what happens if there are no posts to display. The nature of the WordPress loops means that theme authors can add in what they want to display and thereby customize and control the output of their site.

As you would expect, the WordPress Codex includes an extensive discussion of the WordPress loop. Visit http://codex.wordpress.org/The_Loop.

Accessing posts within the WordPress loop

In this recipe, we look at how to create a custom template that includes your own implementation of the WordPress loop.

Getting ready

All you need to execute this recipe is your favorite code editor and access to the WordPress files on your server. You will also need a theme template file, which we will use to hold our modified WordPress loop.

How to do it

Let's assume you have created a custom template. Inside of that template you will want to include the WordPress loop. Follow these steps to add the loop, along with a little customization:

  1. Access the active theme files on your WordPress installation.
  2. Find a template file and open it for editing. If you're not sure which one to use, try the index.php file.
  3. Add to the file the following line of code, which will start the loop:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post();
    ?>

  4. Next, let's display the post title, wrapped in an h2 tag:

    <h2><?php the_title() ?></h2>

  5. Let's also add a link to all posts by this author. Add this code immediately below the previous line:

    <?php the_author_posts_link() ?>

  6. For the post content, let's wrap it in a div for easy styling:

    <div class="thecontent">
    <?php the_content(); ?>
    </div>

  7. Next, let's terminate the loop and add some code to display a message if there were no posts to display:

    <?php endwhile; else: ?>
    <p>Oops! There are no posts to display.</p>

  8. Finally, let's put a complete stop to the loop by ending the if statement that began the code in step number 3, above:

    <?php endif; ?>

  9. Save the file.

That's all there is to it. Your code should look like this:

?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2><?php the_title() ?></h2>
<?php the_author_posts_link() ?>
<div class="thecontent">
<?php the_content(); ?>
</div>
<?php endwhile; else: ?>
<p>Oops! There are no posts to display.</p>
<?php endif; ?>

How it works...

This basic piece of code first checks if there are posts in your site. If the answer is yes, the loop will repeat until every post title and their contents are displayed on the page. The post title is displayed using the_title(). The author's name and link are added with the_ author_posts_link() function. The content is displayed with the_content() function and styled by the div named thecontent. Finally, if there are no posts to display, the code will display the message Oops! There are no posts to display.

There's more...

In the preceding code you saw the use of two template tags: the_author_posts_link and the_content. These are just two examples of the many template tags available in WordPress. The tags make your life easier by reducing an entire function to just a short phrase. You can find a full list of the template tags at: http://codex.wordpress.org/ Template_Tags.

The template tags can be broken down into a number of categories:

  • General tags: The tags in this category cover general page elements common to most templates
  • Author tags: Tags related to author information
  • Bookmark tags: The tag to list bookmarks
  • Category tags: Category, tag, and item description-related
  • Comment tags: Tags covering the comment elements
  • Link tags: Tags for links and permalinks
  • Post tags: Tags for posts, excerpts, titles, and attachments
  • Post Thumbnail tags: Tags that relate to the post thumbnails
  • Navigation Menu tags: Tags for the nav menu and menu tree

Retrieving posts from a specific category

There are times when you might wish to display only those posts that belong to a specific category, for example, perhaps you want to show only the featured posts. With a small modification to the WordPress loop, it's easy to grab only those posts you want to display.

In this recipe we introduce query_posts(),which can be used to control which posts are displayed by the loop.

Getting ready

To execute this recipe, you will need a code editor and access to the WordPress files on your server. You will also need a theme template file, which we will use to hold our modified WordPress loop. To keep this recipe short and to the point, we use the loop we created in the preceding recipe.

How to do it...

Let's create a situation where the loop shows only those posts assigned to the Featured category. To do this, you will need to work through two different processes.

First, you need to find the category ID number of the Featured category. To do this, follow these steps:

  1. Log in to the Dashboard of your WordPress site.
  2. Click on the Posts menu.
  3. Click on the Categories option.
  4. Click on the category named Featured.
  5. Look at the address bar of your browser and you will notice that part of the string looks something like this:&tag_ID=9. On the site where we are working, the Featured category has the ID of 9.

Category IDs vary from site to site. The ID used in this recipe may not be the same as the ID for your site!

Next, we need to add a query to our loop that will extract only those posts that belong to the Featured category, that is, to those posts that belong to the category with the ID of 9. Follow these steps:

  1. Open the file that contains the loop. We'll use the same file we created in the preceding recipe.
  2. Find the loop:

    <?php if ( have_posts() ) : while ( have_posts() ) :
    the_post(); ?>
    <h2><?php the_title() ?></h2>
    <?php the_author_posts_link() ?>
    <div class="thecontent">
    <?php the_content(); ?>
    </div>
    <?php endwhile; else: ?>
    <p>Oops! There are no posts to display.</p>
    <?php endif; ?>

  3. Add the following line of code immediately above the loop:

    <?php query_posts($query_string.'&cat=9'); ?>

  4. Save the file.

That's all there is to it. If you visit your site, you will now see that the page displays only the posts that belong to the category with the ID of 9.

How it works...

The query_posts() function modifies the default loop. When used with the cat parameter, it allows you to specify one or more categories that you want to use as filters for the posts.

For example:

  • query_posts(&query_string.'&cat=5');: Get posts from the category with ID 5 only
  • query_posts(&query_string.'&cat=5,6,9');: Get posts from the category with IDs 5, 6, and 9
  • query_posts(&query_string.'&cat=-3');: Get posts from all categories, except those from the category with ID 3

For more information, visit the WordPRess Codex page on query posts: http://codex.wordpress.org/Function_Reference/query_posts

WordPress 3 Cookbook Over 100 recipes to help you enhance your WordPress site! with this book and ebook
Published: December 2011
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

 

(For more resources on WordPress, see here.)

 

Getting a specific number of posts

If you'd like to control the number of posts displayed on the page, you can do so by using the query_posts() function we introduced in the previous recipe.

Getting ready

All you need to execute this recipe is your favorite code editor and access to the WordPress files on your server. You will also need a theme template file, which we will use to hold our modified WordPress loop. To keep this recipe short and to the point, we use the loop we created in the first recipe in this article.

How to do it...

Let's create a situation where the loop produces only two posts for the page. Follow these steps:

  1. Open the file that contains the loop. We'll use the same file we created in the first recipe in this article.
  2. Find the loop:

    <?php if ( have_posts() ) : while ( have_posts() ) :
    the_post(); ?>
    <h2><?php the_title() ?></h2>
    <?php the_author_posts_link() ?>
    <div class="thecontent">
    <?php the_content(); ?>
    </div>
    <?php endwhile; else: ?>
    <p>Oops! There are no posts to display.</p>
    <?php endif; ?>

  3. Add the following line of code immediately above the loop:

    <?php query_posts($query_string.'showposts=2'); ?>

  4. Save the file.

That's all there is to it. If you visit your site, you will now see that the page displays only two posts (by default, the two most recent posts).

How it works...

Just like in the previous example, we're using the powerful query_posts() function. This time, we use the showposts parameter that allows you to specify how many posts must be displayed.

While this recipe shows you how to hard code the number of posts, you can also control the number of posts per page from within the WordPress dashboard. Accordingly, this recipe should be used only in special circumstances, where the default controls will not meet your needs.

Retrieving posts by date

Another very handy use of the query_posts() function is to get posts according to specific date and time parameters. Retrieving posts by a specific date can be a bit more complex than, for example, getting an exact number of posts, because you sometimes need to use multiple parameters with the query_posts() function. The example in this recipe, however, is rather simple. We'll see more complex uses of query_posts() date and time parameters in the next recipes.

Let's see how to use query_posts() to retrieve and display the posts from a specific date.

Getting ready

All you need to execute this recipe is your favorite code editor and access to the WordPress files on your server. You will also need a theme template file, which we will use to hold our modified WordPress loop. To keep this recipe short and to the point, we use the loop we created in the first recipe in this article.

How to do it...

Let's create a situation where the loop produces only the posts that were published in October. Follow these steps:

  1. Open the template file that contains the loop. We'll use the same file we created in the first recipe in this article.
  2. Find the loop:

    <?php if ( have_posts() ) : while ( have_posts() ) :
    the_post(); ?>
    <h2><?php the_title() ?></h2>
    <?php the_author_posts_link() ?>
    <div class="thecontent">
    <?php the_content(); ?>
    </div>
    <?php endwhile; else: ?>
    <p>Oops! There are no posts to display.</p>
    <?php endif; ?>

  3. Add the following line of code immediately above the loop:
  4. <?php query_posts($query_string.'monthnum=10'); ?>

  5. Save the file.

That's all there is to it. If you visit your site, you will now see that the page displays only the posts published in any October of any year.

How it works...

The monthnum parameter allows you to specify a month number, and retrieve only the posts published in the given period. You can also get posts by day, year, hour, and even minutes and seconds. In the following recipe, we will look at how to combine multiple parameters to narrow in on specific posts.

Here are the date and time parameters which can be used within the query_posts() function:

  • hour: Number from 0 to 24, displays posts made during this time
  • minute: Number from 0 to 59
  • second: Number from 0 to 59
  • day: Number from 0 to 31, shows all posts made, for example on the 15th
  • monthnum: Number from 1 to 12
  • year: Year, show all posts made in for example, 2007

Displaying posts published today

If you publish multiple posts per day, you may very well wish to display your most current posts together, in order to highlight the new content. The WordPress loop makes this possible, with a little help from some easy PHP and the query_posts() function. In this recipe, we show you how to display only those posts published today.

Getting ready

All you need to execute this recipe is your favorite code editor and access to the WordPress files on your server. You will also need a theme template file, which we will use to hold our modified WordPress loop. To keep this recipe short and to the point, we use the loop.

How to do it...

Let's create a situation where the loop produces only the posts that were published today.

Follow these steps:

  1. Open the file that contains the loop. We'll use the same file we created in the first recipe in this article.
  2. Find the loop:

    <?php if ( have_posts() ) : while ( have_posts() ) :
    the_post(); ?>
    <h2><?php the_title() ?></h2>
    <?php the_author_posts_link() ?>
    <div class="thecontent">
    <?php the_content(); ?>
    </div>
    <?php endwhile; else: ?>
    <p>Oops! There are no posts to display.</p>
    <?php endif; ?>

  3. Add the following lines of code immediately above the loop:

    <?php
    $current_day = date('j');
    $current_month = date('m');
    $year = date('Y');
    query_posts($query_string . 'day='.$current_
    day.'&month='.$current_month.'&year='.$year); ?>

  4. Save the file.

If you visit your site, you will now see that the page displays only those posts published on the current date.

How it works...

In the preceding code, we started with creating PHP variables named $current_day $current_month and $year. We then used the query_posts() function to tell the system to only extract those posts that matched the date criteria.

Displaying posts published exactly one year ago

Here's a nice idea to give a second life to your older posts. This recipe automatically displays the posts you published exactly one year ago. The recipe uses some simple PHP, the WordPress loop, and the super-useful query_posts() function.

Getting ready

All you need to execute this recipe is your favorite code editor and access to the WordPress files on your server. You will also need a theme template file, which we will use to hold our modified WordPress loop. To keep this recipe short and to the point, we use the loop we create.

How to do it...

Let's create a situation where the loop produces only the posts that were published exactly one year ago. Follow these steps:

  1. Open the file that contains the loop. We'll use the same file we created in the first recipe in this article.
  2. Find the loop:

    <?php if ( have_posts() ) : while ( have_posts() ) :
    the_post(); ?>
    <h2><?php the_title() ?></h2>
    <?php the_author_posts_link() ?>
    <div class="thecontent">
    <?php the_content(); ?>
    </div>
    <?php endwhile; else: ?>
    <p>Oops! There are no posts to display.</p>
    <?php endif; ?>

  3. Add the following lines of code immediately above the loop:

    <?php
    $current_day = date('j');
    $current_month = date('m');
    $last_year = date('Y')-1;
    query_posts($query_string . 'day='.$current_
    day.'&month='.$current_month.'&year='.$last_year); ?>

  4. Save the file.

If you visit your site, you will now see that the page displays only those posts published on the same day of the previous year.

How it works...

The code in this recipe works exactly the same as that in the previous example. First, we have to use the PHP date() function to get the current day and month number, and then we subtract 1 from the current year. Once done, we simply use query_posts() and the WordPress loop to display the posts.

Using multiple loops

While the default implementation of the WordPress loop uses just one instance of the loop in a template, there is no reason why you cannot use multiple loops in a single template. Using multiple loops allows you the ability to produce specific content items, or lists of contents items in multiple locations on the page – in a sidebar, in the header, in the footer, and so on.

In this recipe, we explore the WP_query() function, and learn how to use it to create multiple loops inside a single template.

Creating multiple loops does have an incremental impact on site performance, so while we say there is "no reason why you cannot use multiple loops," that statement comes with the caveat that you are not running an extreme number of loops on each page!

Getting ready

To execute this recipe you will need a code editor and access to the WordPress files on your server. You will also need a theme template file, which we will use to hold loops we create.

How to do it...

We are going to put two loops in a single template, so there are two parts to this recipe. We're going to set up one loop to show all the posts with the category ID 3. Then we will set up another loop to display the two most recent posts.

In the first part, we create the first loop, using WP_query (). Follow these steps:

  1. Open for editing the template file where you want the loops to appear.
  2. Insert the following lines of code:

    <?php // Loop 1
    $first_query = new WP_Query('cat=9');
    while($first_query->have_posts()) : $first_query->the_post(); ?>
    <h1><a href="<?php the_permalink(); ?>"><?php the_title();
    ?></a></h1>
    <?php the_content(); ?>
    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>

Next, let's set up the second loop. Follow these steps:

  1. Add the following to the template file:

    <?php // Loop 2
    $second_query = new WP_Query('showposts=2');
    while($second_query->have_posts()) : $second_query->the_post(); ?>
    <h1><a href="<?php the_permalink(); ?>"><?php the_title();
    ?></a></h1>
    <?php the_content(); ?>
    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>

  2. Save the file.

If you view the page on your site now, you will see output from both of the loops.

How it works...

WP_Query() provides an alternative method for grabbing posts for display by the loop. It can be used to create any number of loops and is the preferred method for putting multiple loops in a single template. It accepts the same parameters as query_posts(), making it easy to use.

In the preceding code, we created first a single loop that uses the cat variable to pull out the posts in a specific category. The while statement cycles through the posts, producing them for output until there are no more posts that meet the criteria.

The second loop uses the showposts variable to limit the number of posts displayed to the two most recent and then again we see the while statement being used to output the posts.

Both loops close in standard fashion.

Visit the WordPress Codex to learn more about WP_Query() at http://codex.wordpress.org/Class_Reference/WP_Query

Summary

In this article we covered the basics of how to modify your existing theme, and more advanced theming topics.


Further resources on this subject:


WordPress 3 Cookbook Over 100 recipes to help you enhance your WordPress site! with this book and ebook
Published: December 2011
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Ric Shreves

Ric Shreves is a web applications consultant and tech author. He’s been building websites since the mid-90s and writing about tech for almost as long. Ric specializes in open source content management systems and has written texts on each of the big three: WordPress, Joomla! and Drupal.

Ric is the founding partner of water&stone, a digital agency that focuses on new media and online marketing. He works with clients on digital marketing strategy and supervises the SEO implementation team. Ric lives in Bali and divides his time between the island and Singapore.

Books From Packt


WordPress 3 Complete
WordPress 3 Complete

WordPress Plugin Development: Beginner's Guide
WordPress Plugin Development: Beginner's Guide

WordPress 3 Complete
WordPress 3 Complete

WordPress 3 Plugin Development Essentials
WordPress 3 Plugin Development Essentials

WordPress 3 Search Engine Optimization
WordPress 3 Search Engine Optimization

Internet Marketing with WordPress
Internet Marketing with WordPress

WordPress 3 Site Blueprints
WordPress 3 Site Blueprints

WordPress 3.2 Theme Design: Beginner's Guide
WordPress 3.2 Theme Design: Beginner's Guide


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Y
P
R
u
Q
U
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software