Displaying Posts and Pages Using Wordpress Loop

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

WordPress 2.8 Themes Cookbook — Save 50%

Over 100 simple but incredibly effective recipes for creating powerful, custom WordPress themes

£14.99    £7.50
by Lee Jordan Nick Ohrn | June 2010 | Content Management Open Source Web Development WordPress

In this article by Lee Jordan and Nick Ohrn, authors of the book WordPress 2.8 Themes Cookbook, we will cover:

  • Creating a basic Loop
  • Displaying ads after every third post
  • Removing posts in a particular category
  • Removing posts with a particular tag
  • Highlighting sticky posts
  • Creating multiple loops in a single template
  • Displaying only posts in a particular category
  • Styling every other post differently
  • Styling posts in a particular category differently
  • Showing every post in a category on a category archive page

(For more resources on Wordpress, see here.)

The Loop is the basic building block of WordPress template files. You'll use The Loop when displaying posts and pages, both when you're showing multiple items or a single one. Inside of The Loop you use WordPress template tags to render information in whatever manner your design requires.

WordPress provides the data required for a default Loop on every single page load. In addition, you're able to create your own custom Loops that display post and page information that you need. This power allows you to create advanced designs that require a variety of information to be displayed. This article will cover both basic and advanced Loop usage and you'll see exactly how to use this most basic WordPress structure.

Creating a basic Loop

The Loop nearly always takes the same basic structure. In this recipe, you'll become acquainted with this structure, find out how The Loop works, and get up and running in no time.

How to do it...

First, open the file in which you wish to iterate through the available posts. In general, you use The Loop in every single template file that is designed to show posts. Some examples include index.php, category.php, single.php, and page.php. Place your cursor where you want The Loop to appear, and then insert the following code:

<?php
if( have_posts() ) {
while( have_posts() ) {
the_post();
?>
<h2><?php the_title(); ?></h2>
<?php
}
}
?>

Using the WordPress theme test data with the above Loop construct, you end up with something that looks similar to the example shown in following screenshot:

Displaying Posts and Pages Using Wordpress Loop

Depending on your theme's styles, this output could obviously look very different. However, the important thing to note is that you've used The Loop to iterate over available data from the system and then display pieces of that data to the user in the way that you want to. From here, you can use a wide variety of template tags in order to display different information depending on the specific requirements of your theme.

How it works...

A deep understanding of The Loop is paramount to becoming a great WordPress designer and developer, so you should understand each of the items in the above code snippet fairly well.

First, you should recognize that this is just a standard while loop with a surrounding if conditional. There are some special WordPress functions that are used in these two items, but if you've done any PHP programming at all, you should be intimately familiar with the syntax here. If you haven't experienced programming in PHP, then you might want to check out the syntax rules for if and while constructs at http://php.net/if and http://php.net/ while, respectively.

The next thing to understand about this generic loop is that it depends directly on the global $wp_query object. $wp_query is created when the request is parsed, request variables are found, and WordPress figures out the posts that should be displayed for the URL that a visitor has arrived from. $wp_query is an instance of the WP_Query object, and the have_posts and the_post functions delegate to methods on that object.

The $wp_query object holds information about the posts to be displayed and the type of page being displayed (normal listing, category archive, date archive, and so on). When have_posts is called in the if conditional above, the $wp_query object determines whether any posts matched the request that was made, and if so, whether there are any posts that haven't been iterated over.

If there are posts to display, a while construct is used that again checks the value of have_posts. During each iteration of the while loop, the the_post function is called. the_post sets an index on $wp_query that indicates which posts have been iterated over. It also sets up several global variables, most notably $post.

Inside of The Loop, the the_title function uses the global $post variable that was set up in the_post to produce the appropriate output based on the currently-active post item. This is basically the way that all template tags work.

If you're interested in further information on how the WP_Query class works, you should read the documentation about it in the WordPress Codex at http://codex.wordpress.org/Function_ Reference/WP_Query. You can find more information about The Loop at http://codex. wordpress.org/The_Loop.

Displaying ads after every third post

If you're looking to display ads on your site, one of the best places to do it is mixed up with your main content. This will cause visitors to view your ads, as they're engaged with your work, often resulting in higher click-through rates and better paydays for you.

How to do it...

First, open the template in which you wish to display advertisements while iterating over the available posts. This will most likely be a listing template file like index.php or category. php. Decide on the number of posts that you wish to display between advertisements. Place your cursor where you want your loop to appear, and then insert the following code:

<?php
if( have_posts() ) {
$ad_counter = 0;
$after_every = 3;
while( have_posts() ) {
$ad_counter++;
the_post();
?>
<h2><?php the_title(); ?></h2>
<?php

// Display ads
$ad_counter = $ad_counter % $after_every;
if( 0 == $ad_counter ) {
echo '<h2 style="color:red;">Advertisement</h2>';
}
}
}
?>

If you've done everything correctly, and are using the WordPress theme test data, you should see something similar to the example shown in the following screenshot:

Displaying Posts and Pages Using Wordpress Loop

Obviously, the power here comes when you mix in paying ads or images that link to products that you're promoting. Instead of a simple heading element for the Advertisement text, you could dynamically insert JavaScript or Flash elements that pull in advertisements for you.

How it works...

As with the basic Loop, this code snippet iterates over all available posts. In this recipe, however, a counter variable is declared that counts the number of posts that have been iterated over. Every time that a post is about to be displayed, the counter is incremented to track that another post has been rendered. After every third post, the advertisement code is displayed because the value of the $ad_counter variable is equal to 0.

It is very important to put the conditional check and display code after the post has been displayed. Also, notice that the $ad_counter variable will never be greater than 3 because the modulus operator (%) is being used every time through The Loop.

Finally, if you wish to change the frequency of the ad display, simply modify the $after_every variable from 3 to whatever number of posts you want to display between ads.

Removing posts in a particular category

Sometimes you'll want to make sure that posts from a certain category never implicitly show up in the Loops that you're displaying in your template. The category could be a special one that you use to denote portfolio pieces, photo posts, or whatever else you wish to remove from regular Loops.

How to do it...

First, you have to decide which category you want to exclude from your Loops. Note the name of the category, and then open or create your theme's functions.php file. Your functions. php file resides inside of your theme's directory and may contain some other code. Inside of functions.php, insert the following code:

add_action('pre_get_posts', 'remove_cat_from_loops');
function remove_cat_from_loops( $query ) {
if(!$query->get('suppress_filters')) {
$cat_id = get_cat_ID('Category Name');
$excluded_cats = $query->get('category__not_in');
if(is_array($excluded_cats)) {
$excluded_cats[] = $cat_id;
} else {
$excluded_cats = array($cat_id);
}
$query->set('category__not_in', $excluded_cats);
}
return $query;
}

How it works...

In the above code snippet, you are excluding the category with the name Category Name. To exclude a different category, change the Category Name string to the name of the category you wish to remove from loops.

You are filtering the WP_Query object that drives every Loop. Before any posts are fetched from the database, you dynamically change the value of the category__not_in variable in the WP_Query object. You append an additional category ID to the existing array of excluded category IDs to ensure that you're not undoing work of some other developer. Alternatively, if the category__not_in variable is not an array, you assign it an array with a single item. Every category ID in the category__not_in array will be excluded from The Loop, because when the WP_Query object eventually makes a request to the database, it structures the query such that no posts contained in any of the categories identified in the category__not_in variable are fetched.

Please note that the denoted category will be excluded by default from all Loops that you create in your theme. If you want to display posts from the category that you've marked to exclude, then you need to set the suppress_filters parameter to true when querying for posts, as follows:

query_posts(
array(
'cat'=>get_cat_ID('Category Name'),
'suppress_filters'=>true
)
);

Removing posts with a particular tag

Similar to categories, it could be desirable to remove posts with a certain tag from The Loop. You may wish to do this if you are tagging certain posts as asides, or if you are saving posts that contain some text that needs to be displayed in a special context elsewhere on your site.

How to do it...

First, you have to decide which tag you want to exclude from your Loops. Note the name of the tag, and then open or create your theme's functions.php file. Inside of functions.php, insert the following code:

add_action('pre_get_posts', 'remove_tag_from_loops');
function remove_tag_from_loops( $query ) {
if(!$query->get('suppress_filters')) {
$tag_id = get_term_by('name','tag1','post_tag')->term_id;
$excluded_tags = $query->get('tag__not_in');
if(is_array( $excluded_tags )) {
$excluded_tags[] = $tag_id;
} else {
$excluded_tags = array($tag_id);
}
$query->set('tag__not_in', $excluded_tags);
}
return $query;
}

How it works...

In the above code snippet, you are excluding the tag with the slug tag1. To exclude a different tag, change the string tag1 to the name of the tag that you wish to remove from all Loops.

When deciding what tags to exclude, the WordPress system looks at a query parameter named tag__not_in, which is an array. In the above code snippet, the function appends the ID of the tag that should be excluded directly to the tag__not_in array. Alternatively, if tag__not_in isn't already initialized as an array, it is assigned an array with a single item, consisting of the ID for the tag that you wish to exclude. After that, all posts with that tag will be excluded from WordPress Loops.

Please note that the chosen tag will be excluded, by default, from all Loops that you create in your theme. If you want to display posts from the tag that you've marked to exclude, then you need to set the suppress_filters parameter to true when querying for posts, as follows:

query_posts(
array(
'tag'=>get_term_by('name','tag1','post_tag')->term_id,
'suppress_filters'=>true
)
);

Highlighting sticky posts

Sticky posts are a feature added in version 2.7 of WordPress and can be used for a variety of purposes. The most frequent use is to mark posts that should be "featured" for an extended period of time. These posts often contain important information or highlight things (like a product announcement) that the blog author wants to display in a prominent position for a long period of time.

How to do it...

First, place your cursor inside of a Loop where you're displaying posts and want to single out your sticky content. Inside The Loop, after a call to the_post, insert the following code:

<?php
if(is_sticky()) {
?>
<div class="sticky-announcer">
<p>This post is sticky.</p>
</div>
<?php
}
?>

Create a sticky post on your test blog and take a look at your site's front page. You should see text appended to the sticky post, and the post should be moved to the top of The Loop. You can see this in the following screenshot:

Displaying Posts and Pages Using Wordpress Loop

How it works...

The is_sticky function checks the currently-active post to see if it is a sticky post. It does this by examining the value retrieved by calling get_option('sticky_posts'), which is an array, and trying to find the active post's ID in that array.

In this case, if the post is sticky then the sticky-announcer div is output with a message. However, there is no limit to what you can do once you've determined if a post is sticky. Some ideas include:

  • Displaying a special icon for sticky posts
  • Changing the background color of sticky posts
  • Adding content dynamically to sticky posts
  • Displaying post content differently for sticky posts
WordPress 2.8 Themes Cookbook Over 100 simple but incredibly effective recipes for creating powerful, custom WordPress themes
Published: July 2010
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:

(For more resources on Wordpress, see here.)

Creating multiple loops in a single template

In advanced themes, there are often situations where you would want to display multiple Loops consisting of posts with different criteria. When doing so, you should make sure not to alter the normal default Loop or else some template tags will not work appropriately.

How to do it...

First, decide what kind of Loops you want to create. Perhaps you want to create two Loops, based on different categories. Perhaps one Loop should have featured posts while the other has the default posts based on the page URL. For this example, we're going to create two category Loops.

To create the two category Loops, you need to create two separate instances of the WP_Query class. Copy the following code snippet into one of your template files:

<?php
$query1 = new WP_Query(array('cat'=>get_cat_ID('aciform')));
if( $query1->have_posts() ) {
?><h1>Aciform Posts</h1><?php
while($query1->have_posts()) {
$query1->the_post();
?><h2><?php the_title(); ?></h2><?php
}
}
echo '<hr />';
$query2 = new WP_Query(array('cat'=>get_cat_ID('Cat B')));
if( $query2->have_posts() ) {
?><h1>Cat B Posts</h1><?php
while($query2->have_posts()) {
$query2->the_post();
?><h2><?php the_title(); ?></h2><?php
}
}
?>

The above snippet renders output that looks something like the example shown in following screenshot:

Displaying Posts and Pages Using Wordpress Loop

You can see in the above image that there are two major sections. The first consists of the titles of all posts with the category aciform. The second section consists of the titles of all posts with the category Cat B

How it works...

In the above code sample, two new instances of the WP_Query class are created. The first instance is created with parameters specifying that it should contain posts in the category Aciform. The second instance is created with parameters specifying that it should contain posts in the category Cat B

The parameters passed in each case direct the content of the SQL query, which is passed to the underlying WordPress database. You don't really need to know about all of that, but you can learn a lot by looking at how WordPress constructs the query inside of the WP_Query class.

After the instances are created, the basic Loop construct is used. However, you should note that all Loop functions are prefixed with the new object's name. So, when you're using the first WP_Query object that contains posts in Aciform, each Loop function call is preceded with the string $myquery1->. This ensures that the new query object's data is used instead of the global $wp_query object's data.

There's more…

The WP_Query constructor takes a variety of parameters as an array or formatted query string. The parameters are the same as those for the query_posts and get_posts WordPress functions, but there are far too many to even begin to dive into in this recipe. For more information on the available parameters, please see http://codex.wordpress. org/Template_Tags/query_posts#Parameters.

Displaying only posts in a particular category

Often there will be a category that needs to be called on specifically in your WordPress theme. If you don't know the category's ID, you can use the category name to retrieve the correct posts.

How to do it...

First, open the template file that you wish to insert the category Loop into. If you want to highlight a certain category in your theme's sidebar, for example, you would open sidebar.php. Insert your cursor at the appropriate spot, and then add the following code:

<?php
$cat_name = 'My Category Name';
query_posts(array('category_name'=>$cat_name));
if(have_posts() ) {
while(have_posts() ) {
the_post();
}
}
?>

How it works...

The available parameters for the query_posts function are varied and many. In this instance, you take advantage of the category_name parameter to ensure that only posts in the specified category (in this instance, My Category Name) are returned for the Loop. Want to use a different category? Change the value of the $cat_name parameter.

Styling every other post differently

Styling every other post differently is a powerful technique for creating interest in your theme and leading a visitor's eye down the page. The options for styling are endless, but some of the most popular and pervasive options include changing background images, colors, layout items, and more.

How to do it...

Open the template file in which you wish to style posts differently as they are iterated over. In general, you'll insert this functionality into a template like index.php or category.php. Place your cursor where you wish to insert The Loop. Insert the following code:

<?php
if( have_posts() ) {
$alt_post = 'alt-post';
while( have_posts() ) {
the_post();
$alt_post = $alt_post == 'alt-post' ? '' : 'alt-post';
?>
<div class="post <?php echo $alt_post; ?>">
<h2><?php the_title(); ?></h2>
</div>
<?php
}
}
?>

Now open your theme's stylesheet, style.css, and insert the following styles:

/** Styling for alternating posts **/

.post {
background: #990000;
color: #ffffff;
padding: 5px;
}

.alt-post {
background: #000099;
}

Assuming that your stylesheet is linked to your theme appropriately, you should see something like the example shown in the following screenshot:

Displaying Posts and Pages Using Wordpress Loop

How it works...

Each time The Loop is iterated over, PHP checks to see if the $alt_post variable indicates whether an alternate post was rendered on the previous run. If it does, it switches the variable back to the empty string. Otherwise, it sets the variable to alt-post.

When the post container is being printed, it includes a class of post by default, and then prints out the value of the $alt_post variable. If the $alt_post variable was set, the post container then has a class of alt-post in addition to post.

In the theme's stylesheet, you can change the style for the alternate post. In this instance, the background of a regular post will be dark red whereas every alternate post will have a background of royal blue.

Styling posts in a particular category differently

In WordPress, one of the best ways to differentiate content is via the use of categories. In your theme, styling posts from different categories in unique ways will help visitors find what they want quickly and easily.

How to do it...

Decide where you want to check for a particular category. For this example, you'll be checking for the Featured category and appending a little snippet of text. Insert your cursor inside of your Loop, and then add the following code:

<?php
$category_name = 'Featured';
if(in_category($category_name)) {
echo '<div class="featured-icon">Featured</div>';
}
?>

After you detect the special category and print the extra piece of content, you can style it however you want. In this particular case, you may want to use absolute positioning to add a star icon or badge to the post's main content container. Alternatively, you could add a large header that makes the post stand out. There is no limit to what you can do.

How it works...

The in_category function operates on the currently-active post in The Loop. In this instance, you are checking to see if the post is in a category named Featured. If it is, then an extra piece of HTML markup is displayed. This piece of markup could be styled in a way that makes it readily apparent that the post is a featured piece of content.

This technique can be easily adopted for use with other content types: highlighted posts, code snippets, and more. The limit is your imagination.

Showing every post in a category on a category archive page

If you want your category pages to operate as a complete archive of all posts in that category (basically removing any type of pagination), you can make some simple changes to the basic Loop.

How to do it...

Open or create your theme's category.php file. This template file is used to display your category archives. Create a basic Loop by following the directions from the recipe Creating a basic Loop.

Above your Loop, insert the following code:

global $wp_query;
query_posts(
array_merge(
array('nopaging' => true),
$wp_query->query
)
);

How it works...

In the above code snippet, the query_posts function is used to modify the global query object. To ensure that all of the appropriate query parameters are preserved from the original query, the new parameters are merged with the old parameters. The old parameters are kept in the array $wp_query->query.

The nopaging parameter is set to true to indicate that all posts should be returned, and any post limit should be ignored.

See also

  • Creating a basic Loop

Summary

This article taught you about The Loop, the main building block of WordPress. It showed you how to display your content in unique and interesting ways, and also how to change the data that is fetched and presented.


Further resources on this subject:


WordPress 2.8 Themes Cookbook Over 100 simple but incredibly effective recipes for creating powerful, custom WordPress themes
Published: July 2010
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:

About the Author :


Lee Jordan

Lee Jordan is a web developer with a large collection of web technology acronyms on her resume that sound like the names of laundry detergents and cause glazed expressions in school children. She designs and maintains internal and external enterprise-level websites and web-based applications as part of a project team for a privately held technical services company. Her work includes proposing, writing, and editing web content and user guides people actually read. She began her career in 1997 as a web designer after graduating from Florida State University with a Bachelor of Fine Arts, where she swears that she missed at least one home football game while in the computer lab. Lee later convinced Seminole Community College to give her a Web Programming degree in 2003, even though her final project was a Java-based application that actually contained a usable help file. Web development topics or whatever she can think of at the time are posted on her blog at http://leejordan.net.

Nick Ohrn

Nick Ohrn has been creating with WordPress for more than five years and has worked with some of the biggest media companies in the USA.  In his day to day work, he deals with the WordPress source, creates custom themes and plugins, and helps his clients and customers utilize WordPress to run their sites and their businesses.  Nick has a Bachelor’s of Science in Computer Science from the Rose-Hulman Institute of Technology and works full time as a web developer with an emphasis in WordPress development.  He resides in Seattle, WA and works with people and companies from around the world.

Books From Packt

Plone 3 Multimedia
Plone 3 Multimedia

CMS Made Simple 1.6: Beginner's Guide
CMS Made Simple 1.6: Beginner's Guide

JSF 2.0 Cookbook
JSF 2.0 Cookbook

Liferay Portal 6 Enterprise Intranets
Liferay Portal 6 Enterprise Intranets

Django 1.1 Testing and Debugging
Django 1.1 Testing and Debugging

Mahara 1.2 E-Portfolios: Beginner's Guide
Mahara 1.2 E-Portfolios: Beginner's Guide

WordPress 2.9 E-Commerce
WordPress 2.9 E-Commerce

WordPress 3 Site Blueprints
WordPress 3 Site Blueprints

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