20+ Most Wanted WordPress Loop Hacks

The loop is the main process in WordPress, so it is found almost in every theme file. Essentially, it is a PHP code used by the platform to display posts through a theme’ template files. In other words, it’s huge. In fact, it’s critical, because the site will not work without a loop.

Tweaking this set of incredibly powerful features may advance the capabilities of your WordPress site. For example, you can change the way the posts are shown on the homepage and sort them out using specific parameters. Given that the loop is the easiest thing to modify, one can get pretty impressive and creative hacks.

Let’s show you 20+ loop hacks you should use right now to make it happen, without the need to install plugins.

#1. Place Advertising After the First Post

As a blogger, you know very well that ads are one of the best ways to make money. Getting those much needed clicks from visitors is certainly a tricky thing and many bloggers don’t enjoy high click-through rates. Placing ads after the first post can be a good way to increase them, so try this simple tweak.

Replace your loop with the one below. Pay attention, as you must paste the code of the ad there:

<?php if (have_posts()) : ?>
<?php $count = 0; ?>
<?php while (have_posts()) : the_post(); ?>
<?php $count++; ?>
  <?php if ($count == 2) : ?>
          //Insert the code of an ad in this line
          <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; ?>

 

#2. Display Outdated but Popular 1-Year-Old Posts

Most Wanted WordPress Loop Hacks

Some of the posts on your blog, although created a year ago, might still be popular among your readers. For example, it could be a how-to article or some other kind of evergreen content. To ensure that these posts stay popular, you can apply this handy hack.

Insert this code into single.php file:

<?php
$current_day = date('j');
$last_year = date('Y')-1;
query_posts('day='.$current_day.'&year='.$last_year);
if (have_posts()):
    while (have_posts()) : the_post();
       the_title();
       the_excerpt();
    endwhile;
endif;
?>

 

#3. Display Five Latest Sticky Posts in the Loop

Most Wanted WordPress Loop Hacks

The default function allows to stick one post to the front page. The hack below places five sticky posts.

Many bloggers think of sticky posts as featured posts because they allow an entry to display above others. If you want to create your own “Editor’s Picks” category, there is a hack just for that. The code below must be inserted anywhere in the theme to work. You could also change the number to show less posts by replacing the number in the fourth line.

<?php
$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();
        the_title();
        the_excerpt();
    endwhile;
endif;

?>

 

#4. List Posts from a Particular Category

Differentiate posts from the same category with the hack below.

If for some reason you need to differentiate the posts that share the same category (for example, how-to articles for essay writers), insert the following code into the loop file.

<?php foreach((get_the_category()) as $category) {
      	$thecat = $category->cat_ID . ' ';
    	query_posts('child_of='.$thecat);
 if (have_posts()) : while (have_posts()) : the_post();
    //Classic WP loop
 endwhile;endif;
?>

 

#5. Provide Listing of Future Posts

Most Wanted WordPress Loop Hacks

Letting readers know about the upcoming posts might spark their interest and make them return to your blog to read them. If this sounds like a great idea to you, then use the code below to provide a short list of upcoming posts on your WordPress site.

<?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; ?>

 

#6. Get Posts Uploaded on Specific Date

Most Wanted WordPress Loop Hacks

If you often struggle with finding some posts in your feed, you can search for them using a loop. It is possible by inserting the following code that makes the search really easy. Specifically, it retrieves entries posted between two dates that you specify yourself.

<?php
  function filter_where($where = '') {
        $where .= " AND post_date >= '2012-08-19' AND post_date <= '2012-08-11'";
    return $where;
  }
add_filter('posts_where', 'filter_where');
query_posts($query_string);
while (have_posts()) :
      the_post();
      the_content();
endwhile;

?>

 

#7. Display a Loop of Images

The gallery of images on the starting page of a WordPress website is good idea since most of the people appreciate visuals. If your posts contain a lead image, the code below will retrieve them to showcase in a loop.

Insert the following code into functions.php file:

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

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

 

#8. Automatically Remove Posts by Setting an Expiration Date

Suppose you’re running a contest to increase the readership on your blog. When the contest is finished, you publish the results, and most importantly, the answers, or hints, and clues to them. Of course, they should not be accessible to readers forever because you might run another contest in the future, right?

A good way to remove posts even when you forgot about them is scheduling it by setting an expiration date. The loop below replaces your existing one and does just that.

Don’t forget to use the mm/dd/yyyy 00:00:00 format to replace expiration time.

<?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
$expirationtime = get_post_custom_values('expiration');
if (is_array($expirationtime)) {
$expirestring = implode($expirationtime);
}
 
$secondsbetween = strtotime($expirestring)-time();
if ( $secondsbetween > 0 ) {
// For example…
the_title();
the_excerpt();
}
endwhile;
endif;
?>

 

#9. Separate Comments from Trackbacks

Most Wanted WordPress Loop Hacks

A popular entry on your blog will be linked from many other sites. To ensure that the readers can comfortably follow the discussion in the comments section, you should separate comments and trackbacks.

All you have to do is open comments.php and look for the following:

foreach ($comments as $comment) : ?>
// Comments are displayed here
endforeach;

Found it? Great, now replace it with a new code:

<ul class="commentlist">
<?php //Displays comments only
foreach ($comments as $comment) : ?>
<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type == 'comment') { ?>
<li>//Comment code goes here</li>
<?php }
endforeach;
</ul>
 
<ul>
<?php //Displays trackbacks only
foreach ($comments as $comment) : ?>
<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type != 'comment') { ?>
<li><?php comment_author_link() ?></li>
<?php }
endforeach;
 
</ul> 

 

#10. Show Related Posts

Most Wanted WordPress Loop Hacks

Displaying related posts is a good way to increase readership. All you have to do to achieve that is paste a special code into single.php file.

<?php  	
  $backup = $post;  // backup the current object
  $tags = ks29so_get_post_tags($post->ID);
  $tagIDs = array();
  if ($tags) {
    $tagcount = count($tags);
    for ($i = 0; $i < $tagcount; $i++) {
      $tagIDs[$i] = $tags[$i]->term_id;
    }
    $args=array(
      'tag__in' => $tagIDs,
      'post__not_in' => array($post->ID),
      'showposts'=>5,
      'caller_get_posts'=>1
    );
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
      <?php endwhile;
    } else { ?>
      <h2>No related posts found!</h2>
    <?php }
  }
  $post = $backup;  // copy it back
  ks29so_reset_query(); // to use the original query again
?>

 

#11. Determine how Particular Posts are Displayed on Homepage

Most Wanted WordPress Loop Hacks

The vast majority of WordPress themes show all posts in the same way on the starting page. If you don’t like it, however, you can change it and define which ones should be fully displayed and for which only excerpts are enough.

Find index.php file and look for loop there. The following code replaces it:

<?php if (have_posts()) :
    while (have_posts()) : the_post();
         $customField = get_post_custom_values("full");
         if (isset($customField[0])) {
             //Custom field is set, display a full post
              the_title();
              the_content();
         } else {
             // No custom field set, lets display an excerpt
              the_title();
              the_excerpt();
    endwhile;
endif;
?>

 

#12. Display Promotional Content above the Posts on the Homepage

Insert the following code in index.php file to add promotional content.

<div class="content-loop">

 

#13. List all Authors of a Blog in a Page

Most Wanted WordPress Loop Hacks

Just paste this code anywhere in the loop to display the list of all authors.

<ul>
<?php ks29so_list_authors('exclude_admin=0&optioncount=1&show_fullname=1&hide_empty=1'); ?>
</ul>

 

#14. Use Custom Field to Show the Name of Guest Author

If you use guest authors on your blog, it’s very likely that you don’t create a separate page for them. Why don’t just display their name instead?

Insert this code to single.php to do it:

<?php $author = get_post_meta($post->ID, "guest-author", true);
if ($author != "") {
echo $author;
} else {
the_author();
} ?>

 

#15. Make an Image a Mandatory Requirement for Publishing

Posts with Images often enjoy more views than those without. Open your functions.php file to make them mandatory.

add_action('save_post', 'wpds_check_thumbnail');
add_action('admin_notices', 'wpds_thumbnail_error');
 
function wpds_check_thumbnail( $post_id ) {
 // change to any custom post type 
  if( get_post_type($post_id) != 'post' )
      return;
 
  if ( ! has_post_thumbnail( $post_id ) ) {
   // set a transient to show the users an admin message
    set_transient( "has_post_thumbnail", "no" );
   // unhook this function so it doesn't loop infinitely
    remove_action('save_post', 'wpds_check_thumbnail');
   // update the post set it to draft
    ks29so_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
 
    add_action('save_post', 'wpds_check_thumbnail');
  } else {
    delete_transient( "has_post_thumbnail" );
  }
}
 
function wpds_thumbnail_error() {
 // check if the transient is set, and display the error message
  if ( get_transient( "has_post_thumbnail" ) == "no" ) {
    echo "<div id='message' class='error'><p><strong>You must add a Featured Image before publishing this. Don't panic, your post is saved.</strong></p></div>";
    delete_transient( "has_post_thumbnail" );
  }
}

 

#16. Redirect to a Specific Page After Registration

Open functions.php file and add the code below.

function __my_registration_redirect(){
    return home_url( '/my-page' );
}
add_filter( 'registration_redirect', '__my_registration_redirect' );

#17. Insert Ads in Post
Use this code in your functions.php file to wrap ads in a post in any place you want.
Hack
function googleadsense($content){
  $adsensecode = 'Your Ad Codes Here';
  $pattern = '<!-googlead->';
  $content = str_replace($pattern, $adsensecode, $content);
  return $content;      
}
add_filter('the_content', 'googleadsense');

 

#18. Use Shortcodes to Display Ads

Select the place where you wish to insert an ad and paste the following code to functions.php.

function showads() {
    return '
AD’S CODE HERE
';
}
add_shortcode('adsense', 'showads');

 

#19. Display Most Commented Posts

Most Wanted WordPress Loop Hacks

Add the following code to functions.php file to show the posts with the most comments.

function wpb_most_commented_posts() {
ob_start();?>
<ul class="most-commented">
<?php
$query = new
WP_Query('orderby=comment_count&posts_per_page=10');
while($query->have_posts()) : $query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> <span class="wpb-comment-count"><?php comments_popup_link('No Comments;', '1 Comment', '% Comments'); ?></span></li>
<?php endwhile; ?>
</ul>
<?php// Turn off output buffering
$output = ob_get_clean();
return $output; }
add_shortcode('wpb_most_commented', 'wpb_most_commented_posts');
add_filter('widget_text', 'do_shortcode');

 

#20. Enable Featured Image Support

The vast majority of WordPress themes support featured images but if yours don’t, you can enable it by inserting this into functions.php file.

add_theme_support( 'post-thumbnails' );

 

#21. Show Latest Comments

Most Wanted WordPress Loop Hacks

Use this code anywhere in the loop to display five latest comments.

<?php
$query = "SELECT * from $wpdb->comments WHERE comment_approved= '1'
ORDER BY comment_date DESC LIMIT 0 ,5";
$comments = $wpdb->get_results($query);
if ($comments) {
echo '<ul>';
foreach ($comments as $comment) {
$url = '<a href="'. get_permalink($comment->comment_post_ID).'#comment-'.$comment->comment_ID .'" title="'.$comment->comment_author .' | '.get_the_title($comment->comment_post_ID).'">';
echo '<li>';
echo '<div class="img">';
echo $url;
echo get_avatar( $comment->comment_author_email, $img_w);
echo '</a></div>';
echo '<div class="txt">Par: ';
echo $url;
echo $comment->comment_author;
echo '</a></div>';
echo '</li>';
}
echo '</ul>';
}
?>

Ready to Hack?

Use these handy tweaks and enhance the functionality of your WordPress site!

Like the article? Share it.

LinkedIn Pinterest

Leave a Comment Yourself

Your email address will not be published. Required fields are marked *