10 Useful WordPress Loop Hacks


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:

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.

  function filter_where($where = '') {
        $where .= " AND post_date >= '2009-03-17' AND post_date <= '2009-05-03'";
    return $where;
add_filter('posts_where', 'filter_where');
while (have_posts()) :


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:
    $ids = array();
    while (have_posts()) : the_post();
    $ids[] = get_the_ID();
  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:
    query_posts(array('post__not_in' => $ids));
    while (have_posts()) : the_post();
  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:

<?php if (have_posts()) : ?>
<?php $count = 0; ?>
<?php while (have_posts()) : the_post(); ?>
<?php $count++; ?>
  <?php if ($count == 2) : ?>
          //Paste your ad code here
          <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
          <?php the_excerpt(); ?>
   <?php else : ?>
          <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
          <?php the_excerpt(); ?>
  <?php endif; ?>
<?php endwhile; ?>
<?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 fields8, 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:

<?php query_posts('meta_key=review_type&meta_value=movie');  ?>
<?php if (have_posts()) : ?>
<?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.

<?php query_posts('showposts=10&post_status=future'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <span class="datetime"><?php the_time('j. F Y'); ?></span></p>
<?php endwhile;
else: ?><p>No future events scheduled.</p>
<?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.

$current_day = date('j');
$last_year = date('Y')-1;
if (have_posts()):
    while (have_posts()) : the_post();

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:



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 WpRecipes14.

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 post15 to get started.

Template Name: Archives

<?php get_header(); ?>

  <h2><?php $numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
if (0 < $numposts) $numposts = number_format($numposts); ?>
<h2><?php echo $numposts.' recipes published since October 06, 2008'; ?>

  <ul id="archive-list">
    $myposts = get_posts('numberposts=-1&');
    foreach($myposts as $post) : ?>
      <li><?php the_time('m/d/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endforeach; ?>

<?php get_sidebar(); ?>
<?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:

Template Name: Archives

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:

$myPosts = new WP_Query();

while ($myPosts->have_posts()) : $myPosts->the_post(); ?>


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.

$sticky = get_option('sticky_posts');
rsort( $sticky );
$sticky = array_slice( $sticky, 0, 5);
query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) );

if (have_posts()) :
    while (have_posts()) : the_post();


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.

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
  return $first_img;

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

if (have_posts()) :
    while (have_posts()) : the_post(); ?>
        <a href="<?php the_permalink();?>" title="<?php the_title(); ?>" class="img-loop">
        <img src="http://media.mediatemple.netdna-cdn.com/wp-content/uploads/images/wordpress-loop-hacks/<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>" />

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:



  1. 1 http://www.smashingmagazine.com/2009/05/18/100-amazing-free-wordpress-themes-for-2009/
  2. 2 http://www.smashingmagazine.com/2009/05/13/10-custom-fields-hacks-for-wordpress/
  3. 3 http://www.smashingmagazine.com/2009/04/15/10-exceptional-wordpress-hacks/
  4. 4 http://www.smashingmagazine.com/2009/03/04/15-useful-twitter-plugins-and-hacks-for-wordpress/
  5. 5 http://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/
  6. 6 http://www.wprecipes.com/wordpress-loop-get-posts-published-between-two-particular-dates
  7. 7 http://www.wprecipes.com/how-to-insert-adsense-after-the-first-post
  8. 8 http://www.smashingmagazine.com/2009/05/13/10-custom-fields-hacks-for-wordpress/
  9. 9 http://www.johnkolbert.com/wordpress/how-to-only-show-posts-with-a-specific-custom-field/
  10. 10 http://www.wprecipes.com/easily-get-posts-with-a-specific-custom-fieldvalue-on-your-wordpress-blog
  11. 11 http://www.wprecipes.com/how-to-list-future-posts
  12. 12 http://wphackr.com/
  13. 13 http://www.wprecipes.com/how-to-get-posts-published-exactly-one-year-ago
  14. 14 http://www.wprecipes.com/archives
  15. 15 http://www.wprecipes.com/how-to-create-and-use-wordpress-page-templates
  16. 16 http://www.wprecipes.com/fahirsch-asked-how-to-list-all-posts-on-a-page
  17. 17 http://weblogtoolscollection.com/archives/2008/04/13/define-your-own-wordpress-loop-using-wp_query/
  18. 18 http://justintadlock.com/archives/2009/03/28/get-the-latest-sticky-posts-in-wordpress
  19. 19 http://www.wprecipes.com/how-to-get-latest-sticky-posts
  20. 20 http://www.flickr.com/photos/aleksiaaltonen/
  21. 21 http://wordpress.org/support/topic/246893
  22. 22 http://www.wprecipes.com/how-to-get-the-first-image-from-the-post-and-display-it
  23. 23 http://www.smashingmagazine.com/2009/05/18/100-amazing-free-wordpress-themes-for-2009/
  24. 24 http://www.smashingmagazine.com/2009/05/13/10-custom-fields-hacks-for-wordpress/
  25. 25 http://www.smashingmagazine.com/2009/04/15/10-exceptional-wordpress-hacks/
  26. 26 http://www.smashingmagazine.com/2009/03/04/15-useful-twitter-plugins-and-hacks-for-wordpress/
  27. 27 http://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/

↑ Back to topShare on Twitter

This guest post was written by Jean-Baptiste Jung, a 28-year-old blogger from Belgium, who blogs about Web Development on Cats Who Code, about WordPress at WpRecipes and about blogging on Cats Who Blog . You can stay in touch with Jean by following him on Twitter.


Note: Our rating-system has caused errors, so it's disabled at the moment. It will be back the moment the problem has been resolved. We're very sorry. Happy Holidays!

  1. 1

    Nice Article… tips and tricks always comes in handy!!

    DKumar M.

  2. 2

    nice article..thanks alot..

  3. 3

    very cool hacks, thanks for those tips :D

  4. 4

    Nice article. Although using new WP_Query is an easier method of having multiple queries running on a page. It’s used like this:

    $newsarchive = new WP_Query(‘cat=1&showposts=20′);
    if($newsarchive->have_posts()) : while($newsarchive->have_posts()) : $newsarchive->the_post();

    Then you can use your various post tags such as the_content(); and the_title();, and finish it off with

    endwhile; endif;

  5. 5

    Thanks for useful post,.. I’m using some of proposed tips.

  6. 6

    Great Tips. I am looking for one tip not mentioned. I am bringing in posts to wordpress via RSS. How can I include a generic image per post via a custom field?

  7. 7

    Can’t get enough of this kind of posts guys!
    I love wordpress and often need to hack it ;-)

    Thank you very much!

  8. 8

    Thanks for this one. I have been doing web development for a long time but I am just now emmersing myself in WordPress. This gave me some great info I will definitely be using. By the way, I like how you don’t allow blatant ads through your comments. Good work. The web needs more like you.

  9. 9

    great post, you should also make mention to the rewind_posts(); for using multiple loops on a page. fixed many headaches for me

  10. 10

    Thanks great post. The loop is most powerful!

  11. 11

    wordpress stuff… YUMMY !!

  12. 12

    Great post! Some really cool tips in here.

    How about some tips for sidebar? Maybe a follow up post… :)


  13. 13

    I’m gonna use the tip n.10 for sure on the next project!!! :D

    I use a trick quite similar to the tip n.3 to insert ads every x posts here is the code :

    if (have_posts()) :
    $count = 0;
    while (have_posts()) : the_post();
    if ($count%2== 0) :
    //Paste your ad code here

    this make your ads compare every 2 posts , change the value next to the % for have your ads every 3 , 4 , 5 and so on ..

  14. 14

    Waho… very very usefull. Thanks a lot !

  15. 15

    Great Post!

  16. 16

    Would be great if you could show a way to display the posts in order of the most recent comment, similar to how a forum works.

  17. 17

    What happened to your CSS? Your h2 Headlines are as small as the text since some days?
    So it is not quite lucid :-(

  18. 18

    awesome great thanks
    i am working on new WordPress codes website http://wpcodes.com :)

  19. 19

    Great article. The WordPress loop is super sexy. :D

  20. 20

    great post, thanks

  21. 21

    Jean – It is amazing and endless – the number of plug-ins, themes, and widget that exist and continue to be added, which makes Word Press a remarkable platform for bloggers. Your post opened my eyes up to a whole new realm of posibilities.

    Thank you!


  22. 22

    Thanks..useful stuff like always :)

  23. 23

    Giacomo Ratta [ITA]

    June 10, 2009 8:31 am

    Great ideas (and their implemetations)!
    I like customize WordPress also, and I create a more useful archive and 404 pages on my blog.
    I believe I will write a post about my tecniques…

  24. 24

    I wanted to see if you had HTML to add a contact form in the sidebar or in the regular text of the page. Thanks

  25. 25

    #3 is a nice little trick

  26. 26

    Very useful tutorial.

    On tip 3 you have code repetition that isn’t really required you could just add an if on the add and place it under the text body

  27. 27

    I love these kinds of posts. Thank you very much :-)

  28. 28

    This is excellent! Even as a veteran PHP developer, some of these caught me off-guard with their simplicity.

  29. 29

    Jean-Baptiste– in a word, thanks.

    Echoes to most of the ones above as well. Very well-written and worded post.

    Proving again the means by which Smashing keeps addicts, and adds more daily.

  30. 30

    Jean-Baptiste Jung

    June 10, 2009 12:34 pm

    Thanks everyone for the comments! I’m glad (most of) you found this article usefull!

  31. 31

    Is there an easy way to post multiple loops that each display posts from different categories?

  32. 32

    Out of a programmer’s view, the way WordPress is designed is just a insane. I actually like the product in many ways but the programmer who build it to begin with must have been high on crack.

  33. 33

    WordPress is simple and powerful. What a strange combination…

  34. 34

    Hey, thanks for dropping ads into your RSS feed. Now that subscribing is no longer a way of avoiding getting slammed with advertising on this site I’ll just stop subscribing.


  35. 35

    Sweet Serendipity

    June 10, 2009 6:30 pm

    Sweet hacks. Well written article and very helpful. Thanks for sharing this info!

  36. 36

    Nice content! Congratulations for sharing this!

  37. 37

    Great tips. Going to have to implement some of these in my upcoming theme for my personal website.


  38. 38

    Great post! Thanks for the tips, I’ll definitely use the “Use More Than One Loop On A Page, Without Printing Duplicate Posts” on my next project.

  39. 39

    Great Post! Latest version of WordPress has been released. In addition to over 790 bugs fixes, there are improvements in themes, widgets, taxonomies, and overall speed. W3Avenue has compiled a list of resources for WordPress developers that will help them quickly upgrade their themes or plugins to accommodate latest features:


  40. 40

    Thanx, i use a lot of customized loops and tricks in my blog

  41. 41

    Lakshmi Mareddy

    June 13, 2009 6:46 pm

    Jean Baptiste! Way to go.. pretty cool features, and yes, I shall be including some of the tips for my next theme!!! Many Thanks….

  42. 42

    Good stuff! Thanks for sharing


  43. 43

    Great hacks! Can’t wait to put the Loop Archive page to use. Posts on new hacks for WordPress never get old :)

  44. 44

    Delightful Shopping Admin

    June 17, 2009 12:52 am

    Excellent WordPress Tweaks.
    Whenever i run across these type of Posts listing Tweaks, i am always amazed and humbled by genius programmers out there like Jean-Baptiste Jung! Thank you Jean-Baptiste for sharing with the rest of us!

  45. 45

    Hi, very interesting post!

    I have a question for you. Suppose one would like to hide all published posts (but the ones that should be shown in the current page) putting them within

    <div style="display=none!important;">

    The posts have to be ordered cronologically. How would you do it? I guess it needs three loops.


  46. 46

    How about getting the number of posts the returned by the query?

  47. 47

    Hi, this is a wonderful entry, I don’t know if I can ask question here but I think you could probably answer if fairly easily.

    I’m currently making this wordpress theme

    I wanted to give the client the ability to change out the promo image (at the top), the left container events posts, and the right container news posts. I have three different loops for each using category to distinguish them. Here is an example of my events post loop (used in the left container) :

    Not Found
    Sorry, but you are looking for something that isn’t here.

    My problem is that I only want to show 4 posts in the events container, 1 post (the image) in the promo container, and 3 posts in the news container. I have tried various plug-ins and the don’t seem to work. Also I tried the here but it controls all posts, not just the events.

    Can any one out there help me or point me in the right direction? Excuse my lack of programming lingo, I’m more of a designer dabbling in code.

    Thanks so much.

  48. 48

    well… it appears I can’t post my code in here.

  49. 49

    Nice Post..

    How to display the posts in coloum wise..by taking the posts id from outside file like..assume
    post.txt contains post ids..
    reading the file and displayig the posts where ever we want…
    using the query_posts();


  50. 50

    Views in Drupal can do this kind of stuff and a boat load more without hacking the shit out of it. WordPress is a blog engine at best, toy CMS at worst.

  51. 51

    Great Information … will give them a try.

  52. 52

    LOVE the no duplicate posts in multiple loops solution!

    I have been looking for this and although I have found many “solutions” this is the only one that would work in my Sidebars!

    Ed @ FoundByDesign

  53. 53

    Great collection. Just using the “Creat a Loop of Images” code. But there’s a doubled “empty” in the code. Need to remove one. Looks like this:
    if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";

  54. 54

    I have a short question. For a project at the company I work, I need a Script that shows up the search result count of a wordpress blog, outside of it. What I mean is in a separate website, that is used as a metasearch engine, I have to show the search result number from a wordpress blog. There’s different approaches that I have in mind. I could maybe use Tip Nr. 8 which means creating my own WordPress Loop using The WP_Query Object in a File at the root folder and then inlude this php file in the separate website? or as a second approach I could try and modify this script from the wordpress forum:


    so that it pulls, not the the number of posts in the WP database but the search results count. Only I don’t know how to achieve it.

    Of course the query:

    // ...Formulate the query
    $query = "
    SELECT *
    FROM `wp_posts`
    WHERE `post_status` = 'publish'
    AND `post_password` = ''
    AND `post_type` = 'post'";

    // ...Perform the query
    $result = mysql_query( $query );

    // ...Check results of the query and terminate the script if invalid results
    if ( !$result ) {
    $message = 'Invalid query.' . "n";
    $message .= 'Whole query: ' . $query ." n";
    die ( $message );

    // Init a variable for the number of rows of results
    $num_rows = mysql_num_rows( $result );

    // Print the number of posts
    echo "$num_rows Posts";

    hast to be different, but I´m really not a php master. Thank you very much for your support!

    • 55

      Wow. It’s a lot simpler than that to count WordPress’ search results, here:
      global $wp_query;
      $count = sizeof( $wp_query->posts );
      //var_dump($wp_query);// The WP Query Object
      var_dump($wp_query->posts); // The WP Query Object’s ‘posts’ property (note the plural)

      If you drop that snippet in your search template, it will output the properties of the ‘$wp_query’ variable, specifically the ‘posts’ property of the object. This is an array that stores a collection of the returned posts from the search query, which you can do a number of things with once you access it, including (*drumroll*), *count* the number of posts in that array using either PHP’s ‘count()’ or ‘sizeof()’ function.

      • 56

        and, one step quicker to get the post count returned, rather than using size of the posts array, you can just use:

        $count = $my_query->post_count;

  55. 57

    Thanks for this. It means I can stop pulling my hair out and solve my problem–its bugged me for 3 weeks

  56. 58

    Hi, i’m using the second hacks and it’s all ok but all posts remain in the front page: the 11th post mot appear in the second page but in the firste. Why?

    Exscuse me for my bad english.

  57. 59

    Do you know how I should modify the Printing Duplicate Posts tip to have it show one category and not the one I’ve already shown?

  58. 60

    …. some really cool WP hacks…. thanks for posting them !!

  59. 61

    Moscaliuc Lucian

    August 23, 2010 3:09 am

    How can I order category archive posts by subcategories and then by meta value?
    Like This:

    Archive for category 1:

    Sucat 1 (child of 1)

    1.(metavalue) Post 1
    2.(metavalue) Post 2
    3.(metavalue) Post 3

    Sucat 2 (child of 1)

    1.(metavalue) Post 4
    2.(metavalue) Post 5
    2.(metavalue) Post 6

  60. 62


    Is it possible to use the ‘duplicate posts in loop’ method in two different template files? i.e. one in the main loop and then test against the $do_not_duplicate in the footer.php file?

    I can’t seem to get it working…

  61. 63

    To get number of posts , you can do something in wp-includesquery.php

    Add the below lines after have_posts() . There are two functions .
    around line 2601 , the first one is inside the class.

    function get_post_count() {
    return $this->post_count;

    Around line 638. This is not in class .

    function get_post_count() {
    global $wp_query;

    return $wp_query->get_post_count();

  62. 64

    Really nice list of hacks, I thinks all this tips gotta help me to do my design idea project :D

  63. 65

    Finally, I printed this tuts into a pdf file. Thanks a lot :)

  64. 66

    “Use More Than One Loop On A Page, Without Printing Duplicate Posts” – this is exactly what I’m looking for! Thank you so much!

  65. 67

    however, there are problems with the “Display Posts Published One Year Ago” hack:
    1: the month isn’t specified, so you get all articles written last year on the x-th day of every month
    2: if no article was written exactly on the same day as today one year before, the loop doesn’t return any article…

    … and that’s precisely what I’m struggling about : I’d like to get the one and only article that was written just before today, one year ealier…

    Any idea ?

  66. 68

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

    I tried the advice on this page, and similar advice in the Codex and on several other pages regarding multiple loops, but could not get it working properly, until I found help on the WordPress forum.

    I am using a child theme of Twenty Ten with the second loop in the sidebar listing recent posts (minus the single post or posts on an archive page). It worked for two loops in index.php, just not for a second loop in sidebar.php, UNTIL I declared the variable storing the array of Post ID’s as a global variable before starting up the main loop, like so, using $do_not_duplicate in place of $ids:

    global $do_not_duplicate;
    $do_not_duplicate = array();
    while (have_posts()) : the_post();
    $do_not_duplicate[] = get_the_ID();

    Then the second loop in the sidebar starts with:

    global $do_not_duplicate;
    $postroll_query = new WP_Query(array(
    ‘post__not_in’ => $do_not_duplicate,
    ‘posts_per_page’ => 8 ));
    while( $postroll_query->have_posts() ) : $postroll_query->the_post();

    I also threw in the recommended wp_reset_query(); after the second loop.

    After much pulling of hair, it works now, for which I am very grateful.

    P.S. I’m not a coder, just a trial and error WordPress-er, so if there are better solutions, please post them; this solution just worked for me, and I thought it might help someone else out.

  67. 69

    Nice post..Awsome.. :)

  68. 70

    thank you. It’s awesome…

  69. 71

    On #10, with photos – it works just the way I need it to, but is it possible to force the thumbnail size of that image? Basically I have the image at Large size in the post, but on the homepage where I’m pulling this, I’d like if it used the 74×74 size I defined in the media section.


  70. 72

    Having read this I believed it was extremely enlightening. I appreciate you spending some time and effort to put this short article together. I once again find myself personally spending a lot of time both reading and commenting. But so what, it was still worthwhile!

  71. 73

    Loop #2 was very useful to me, but in order for my pagination to function properly I had to alter this line of code from:

    query_posts(array(‘post__not_in’ => $ids));

    This was messing up my pagination. So I changed it to this:

    query_posts(array(‘post__not_in’ => $ids, ‘paged’ => $paged));

  72. 74

    Having read this I thought it was very informative. I appreciate you spending some time and energy to put this article together. I once again find myself personally spending a lot of time both reading and commenting. But so what, it was still worth it!

  73. 75

    Nice Post!!!!!!
    it was very informative.

  74. 76

    Hercules Iorwuese

    October 20, 2013 1:34 pm


    I used this hack “Use More Than One Loop On A Page, Without Printing Duplicate Posts” to code a theme with a featured column and general blog index listing on the index.php

    However I did observed that when I included one of the loops in a sidebar template file before including it into the index.php template, the system failed completely as the same posts that appeared in the sidebar template file also appeared in the main blog index lists.

    I corrected this by using the two loops on the same index.php template file and the result is awesome!

    But I wish to understand why this is do. Could someone kindly explain why the first loop can not be separated in a sidebar template and included using the get_sidebar(‘featured’) tag?

    Thanks very much.

↑ Back to top