free website hit counter
RSS Feed     Twitter     Facebook
Room 09 Shop
Read Detail
Live Demo
Buy Now
Simplicity eCommerce
Read Detail
Live Demo
Buy Now
Bazar Shop
Read Detail
Live Demo
Buy Now
The Retailer
Read Detail
Live Demo
Buy Now
Phomedia E-Commerce
Read Detail
Live Demo
Buy Now

10 Useful Loop Hacks of WordPress

Font size:
  • Sharebar

The loop is a very important aspect of WordPress blogs. In fact, the loop is what allows you to get posts from your WordPress database and print them on the screen. A set of useful and user-friendly functions, the loop is incredibly powerful. With it, you can get a single post, a list of posts ordered by date, title or category, a list of posts written by a specific author and much more.

In this article, we’ll show you 10 useful things you can do with the WordPress loop to make your blog even more powerful than it is right now.

You may be interested in the following related posts:

(Smashing’s note: If you are looking for a good book on mobile, this is the one. Our brand new book on best design and coding practices for mobile, Responsive Web design and UX design for mobile. Get it now!)

1. Get Posts Published Between Two Dates

Image source: Shutterstock

The problem.
The loop and the query_posts() WordPress function allow you to easily retrieve a list of posts published in a specific week or month. Unfortunately, getting posts published between, for example, March 17 and May 3 isn’t that easy. Let’s solve this problem.

The solution.
Simply paste the following code wherever in your theme you’d like to display the list of posts published between two dates. Don’t forget to replace the dates in the example with yours.

01 <?php
02   function filter_where($where = '') {
03         $where .= " AND post_date >= '2009-03-17' AND post_date <= '2009-05-03'";
04     return $where;
05   }
06 add_filter('posts_where', 'filter_where');
07 query_posts($query_string);
08 while (have_posts()) :
09       the_post();
10       the_content();
11 endwhile;
13 ?>

Code explanation.
To achieve this hack, I first create a function named filter_where(), which contains an SQL “WHERE” condition. Then, before starting the loop, the filter_where() function is hooked into WordPress’ post_where() function.

As a result, the “WHERE” clause contained in the filter_where() function is added to the end of the SQL query contained in the post_where() function, which means that the loop will return posts published only between the two dates specified in the filter_where() function.


2. Use More Than One Loop On A Page, Without Printing Duplicate Posts


The problem.
Most modern themes and all “magazine” themes display at least two loops on the blog’s home page; these can be used, for example, for a “featured posts” section. While using two loops is very easy to do, preventing duplicate posts from displaying is not… until, that is, you learn this easy method of preventing them.

The solution.

  1. Let’s start with the first loop. Nothing hard here: we’re just going to get the eight most recent posts using the showposts parameter. Open the index.php file, and paste the following code to output your “featured” posts:
    1 <?php
    2 query_posts('showposts=8');
    3 $ids = array();
    4 while (have_posts()) : the_post();
    5 $ids[] = get_the_ID();
    6 the_title();
    7 the_content();
    8 endwhile;
    9 ?>
  2. Once that’s done, it’s time to apply our second loop and get all posts, excepted the ones we have already outputted in the first loop:
    1 <?php
    2 query_posts(array('post__not_in' => $ids));
    3 while (have_posts()) : the_post();
    4 the_title();
    5 the_content();
    6 endwhile;
    7 ?>
  3. Save your index.php file and admire the results!

Code explanation.
The first loop starts with the very useful query_posts() function, which allows you to specify a wide range of parameters to be used by the loop. The showposts parameter allows you to get the specified number of posts. Just before the loop starts, I create a PHP array named $ids, which will receive all IDs of the posts returned by this loop.

Like the first one, the second loop uses the query_posts() function with the post__not_in parameter. This parameter allows you to specify a list of posts that you don’t want to be displayed, in the form of a PHP array. As you probably saw, I passed the $ids array to this parameter so that any posts returned by the first loop would be returned again by the second loop.

3. Insert Ads After The First Post


The problem.
Advertising is a good way to monetize your blog. But to get advertisers, your ads must receive clicks by your visitors. Many bloggers display ads on the blog sidebar, footer or header, which isn’t always great with click-through rates. To obtain more clicks on your ads and make your advertisers happy, inserting them after the first post is a good idea. Let’s see how to do this in the WordPress loop.

The solution.
Simply use the following loop instead of your current loop. Don’t forget to insert your ad code on line 6:

01 <?php if (have_posts()) : ?>
02 <?php $count = 0; ?>
03 <?php while (have_posts()) : the_post(); ?>
04 <?php $count++; ?>
05   <?php if ($count == 2) : ?>
06           //Paste your ad code here
07           <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
08           <?php the_excerpt(); ?>
09    <?php else : ?>
10           <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
11           <?php the_excerpt(); ?>
12   <?php endif; ?>
13 <?php endwhile; ?>
14 <?php endif; ?>

Code explanation.
Since the early days of programming, integer variables have been a common operation to use as a counter. This is exactly what I’ve done here: just before the loop starts, a $count variable is created. This variable increases by an increment of 1 with each result returned by the loop.

Then, you just have to add an if structure (line 5) and see if $count is equal to 2. If it is, it means that the first post has already been returned and we can display the ads.


4. Get Posts With A Specific Custom Field And Specific Value


The problem.
Because of the popularity of WordPress’ custom fields, you will often want to be able to output a list of posts with a specific custom field and specific value. While so simple for advanced WordPress users, beginners continue to ask me about this on my blogs. So, here’s the correct and easy way to achieve this.

The solution.
Not hard at all. We only have to use the query_posts() function with the meta_key and meta_value parameters:

1 <?php query_posts('meta_key=review_type&meta_value=movie');  ?>
2 <?php if (have_posts()) : ?>
3 <?php while (have_posts()) : the_post(); ?>

Code explanation.
Definitely nothing hard here. To get only posts with a specific custom field and specific value, you have to use the query_posts() function with the meta_key and meta_value parameters. The meta_key value is the name of the desired custom field, and meta_value is the desired value.


5. List Upcoming Posts


The problem.
Thanks to the “schedule post” option, our favorite blogging platform allows us to write a post and schedule it to be published later. To make sure your readers come back to your blog or subscribe to your RSS feed, listing your upcoming posts is a good idea.

The solution.

1 <?php query_posts('showposts=10&post_status=future'); ?>
2 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
3         <h2><?php the_title(); ?></h2>
4         <span class="datetime"><?php the_time('j. F Y'); ?></span></p>
5 <?php endwhile;
6 else: ?><p>No future events scheduled.</p>
7 <?php endif; ?>

Code explanation.
To achieve this, I used the query_posts() function with an interesting parameter called post_status. The post_status parameter allows you to get posts according to their published status (“published,” “draft” or, like in this example, “future”). Because I also added the showposts=10 parameter, this code will not return more than 10 upcoming posts.


6. Display Posts Published One Year Ago


The problem.
Many blogs have so much content and some very good older posts that should not be ignored. But most visitors end up seeing only the freshest content.

The solution.
If your blog is relatively old, why not showcase posts that were published over a year ago? Doing this is simple. Just insert the following code in your blog sidebar or single.php file.

01 <?php
02 $current_day = date('j');
03 $last_year = date('Y')-1;
04 query_posts('day='.$current_day.'&year='.$last_year);
05 if (have_posts()):
06     while (have_posts()) : the_post();
07        the_title();
08        the_excerpt();
09     endwhile;
10 endif;
11 ?>

Code explanation.
The first thing was to get today’s number, which we did on line 2, using the PHP date() function. Then, we had to get last year’s number, which we easily did by taking date('Y') (which returns the current year) and subtracting 1, giving us last year’s number.

Once that’s done, we only have to pass the $current_day and $last_year variables to the day and year parameters of the query_posts WordPress function.

As an aside, if for some reason you want only today’s posts, just delete line 3 and replace line 4 with the following:

1 query_posts('day='.$current_day);


7. Use The Loop To Create An “Archive” Page Template


The problem.
As noted in the previous hack, a common problem on blogs is that it is hard for readers to find content published a while ago.

To help my readers finding what they’re looking for, I created a WordPress page template that displays a list of all posts ever published on my blog. You can see a live demo of this hack on WpRecipes.

The solution.
If you don’t know what a page template is or how to use one on your blog, you should first read this quick post to get started.

01 <?php
02 /*
03 Template Name: Archives
04 */
05 ?>
07 <?php get_header(); ?>
09     <h2><?php $numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
10 if (0 < $numposts) $numposts = number_format($numposts); ?>
11 <h2><?php echo $numposts.' recipes published since October 06, 2008'; ?>
12     </h2>
14     <ul id="archive-list">
15         <?php
16         $myposts = get_posts('numberposts=-1&');
17         foreach($myposts as $post) : ?>
18             <li><?php the_time('m/d/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
19         <?php endforeach; ?>
20     </ul>
22 <?php get_sidebar(); ?>
23 <?php get_footer(); ?>

Code explanation.
The first thing to do is create a “page template.” A page template is created by adding the following lines to the top of the file:

1 <?php
2 /*
3 Template Name: Archives
4 */
5 ?>

An interesting part of this code is the post counter (line 8). This is done by creating a PHP variable named $numposts and using the $wpdb object to get the result from the SQL query sent to WordPress database.

Once that’s done, we simply have to display the $numposts variable, and the total number of posts on your blog will be printed on the screen.

Now, let’s have a closer look at the loop used in this code. As you probably saw, this code doesn’t use the classic loop but rather uses the get_posts() function. get_posts() is a simple tag for creating multiple loops. We first take all posts from the engine and for each of these posts we present the date, the link and the title of the post. Simple and effective.


8. Create Your Own WordPress Loops Using The WP_Query Object


The problem.
The classic WordPress loop, which is used in most hacks in this post, is both useful and user-friendly. However, particularly when using a lot of custom loops (for example, in complex “magazine” layouts), you risk problems with resetting, offsetting, invalid conditional tags and other annoyances.

The solution.
The solution is to use the WP_Query object and create your very own loop:

01 <?php
02 $myPosts = new WP_Query();
03 $myPosts->query('showposts=5');
05 while ($myPosts->have_posts()) : $myPosts->the_post(); ?>
06    the_title();
07    the_content();
08 endwhile;
10 ?>

Code explanation.
The code above displays your five most recent posts. Here is what this code does in detail:

  • On line 2, I created a new WP_Query object, named $myPosts.
  • On line 3, I executed a query using the showposts parameter to get only the five most recent posts.
  • On line 5, our custom loop starts.
  • On line 6 and 7, we simply print some basic post information (title and post content)
  • On line 8, our custom loop ends.

If you want to display more or less than five posts, simply change the value of the showposts parameter on line 3.


9. Get Only The Latest Sticky Posts


The problem.
Introduced in WordPress 2.7, sticky posts are a very cool feature of our favorite blogging platform. A lot of WordPress users ask how to get only sticky posts in the loop.

The solution.
To display your five most recent sticky posts, just paste the following code anywhere in your theme files. If you want to display more or less sticky posts, just change the 5 to the desired value on line 4.

01 <?php
02 $sticky = get_option('sticky_posts');
03 rsort( $sticky );
04 $sticky = array_slice( $sticky, 0, 5);
05 query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) );
07 if (have_posts()) :
08     while (have_posts()) : the_post();
09         the_title();
10         the_excerpt();
11     endwhile;
12 endif;
14 ?>

Code explanation.
The first thing was to get all sticky posts (line 2). Then, we re-ordered them, displaying the most recent ones at the top, using the PHP rsort() function (line 3). On line 4, we got the five most recent sticky posts. As mentioned, you can change the amount of posts retrieved by changing 5 to any other value.

Once that’s done, we use the query_posts() function to control the WordPress loop. Using the post__in parameter, we can make sure that the retrieved posts are contained in an array of values. This array is indeed our $sticky variable. Then, we just set up a basic loop and display the desired information from the post on the screen.


10. Create A Loop Of Images


The problem.
Nowadays, most blogs display post excerpts on the home page along with an image. How about being even more original and providing readers with a nice “gallery” page, listing however many of your recent posts, and displaying each post’s lead image? Of course, we can easily achieve this with custom fields; but believe it or not, custom fields aren’t necessary.

The solution.
To create our loop of images, we first need a PHP function that can grab the first image from each post and return its URL. To do this, paste the following function in your functions.php file. Don’t forget to define a default image on line 10.

01 function catch_that_image() {
02   global $post, $posts;
03   $first_img = '';
04   ob_start();
05   ob_end_clean();
06   $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
07   $first_img = $matches [1] [0];
09   if(empty($first_img)){ //Defines a default image
10     $first_img = "/images/default.jpg";
11   }
12   return $first_img;
13 }

Once you’ve saved the functions.php file, you are now ready to display your image loop.

1 <?php
2 if (have_posts()) :
3     while (have_posts()) : the_post(); ?>
4         <a href="<?php the_permalink();?>" title="<?php the_title(); ?>" class="img-loop">
5         <img src="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>" />
6         </a>
7     endwhile;
8 endif;
9 ?>

Code explanation.
The first part of this code is the catch_that_image() function that we inclued in our functions.php file. Basically, this function parses the post’s content using the $post and $posts global variables as well as a PHP regular expression. If no image is found (i.e. the post doesn’t have one), the default image URL is returned. Otherwise, the function returns the URL of the first image in the post.

The second part of the code is the loop itself, and there’s absolutely nothing hard about it. In fact, it is just a basic loop with no text content is displayed. Instead, the first image from the post is displayed, using the catch_that_image() function.


Related posts

You may be interested in the following related posts:

Share with: Twitter Delicious Facebook Digg Stumbleupon Wordpress Googlebuzz Myspace Gmail Newsvine Favorites More
You can leave a response, or trackback from your own site.
Some More Popular News

Leave a Reply


Recent Search
Copyright© 2015 WordPress Planet | All Right Reserved.