The thing that allows the user to grab posts from the database of WordPress and post them right there on the screen is what we know as ‘the loop’. This is without a doubt one very useful set of functions and if used properly, can be a powerful tool you can use to combine and manage your posts. Learning the loop hacks can help you order posts by date, category, title, author, etc.
Table of Contents
8 WordPress Loop Hacks for Programmers
This article will teach you eight amazing tricks you can do by using the WordPress loop.
1. Use Several Loops on One Page
Many themes provide you with a minimum of two loops on your home page. Using them is simple, but it often results in duplicate posts. Fortunately, there is a way to prevent this from happening.
Firstly, you need to use the showposts parameter to get the recent posts. In the index.php file, paste this code to do this:
<?php
query_posts(‘showposts=8’);
$ids = array();
while (have_posts()) : the_post();
$ids[] = get_the_ID();
the_title();
the_content();
endwhile;
?>
Secondly, apply the other loop to get the posts you need, excluding the ones you outputted with the first code.
<?php
query_posts(array(‘post__not_in’ => $ids));
while (have_posts()) : the_post();
the_title();
the_content();
endwhile;
?>
That’s it! You can now get a specified posts number by using the showpost parameter, and use several loops on one page without duplicating the posts.
2. Get the Posts Published Between 2 Dates
Wondering how to get the posts published between two dates? So far, WordPress presents you with a function you can use to retrieve all posts which were published in one month or one week. But, if you want to set two dates and find those in between, here is what you can do.
Choose a spot in your theme where you want to place the list you are looking for.
<?php
function filter_where($where = ”) {
$where .= ” AND post_date >= ‘XXXX-XX-XX’ AND post_date <= ‘XXXX-XX-XX'”;
return $where;
}
add_filter(‘posts_where’, ‘filter_where’);
query_posts($query_string);
while (have_posts()) :
the_post();
the_content();
endwhile;
?>
3. Insert an Ad Right After Your First Post
Advertising is one of the most popular ways to earn money from a blog. However, you need to include your ads in your posts for visitors to click on them and to attract the advertisers.
‘’Surely, you can add the ads on the sidebar, header or footer of your blog. But, this isn’t the very best ways to increase the number of ad clicks. To get more clicks for your ads and increase the number of advertisers and income, you should definitely consider adding them after your post.’’ – advices Juan Bayer, a WordPress expert from a professional essay writing service.
Here is the code you can use to do this:
<?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; ?>
4. List the Upcoming Posts
Scheduling posts is very helpful and highly appreciated by all those who cannot sit down and publish posts manually each day. However, you probably want to create an ‘upcoming posts’ lists for your visitors to see. Here is the code you can use for this:
<?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; ?>
5. Set a Post Expiration Date
Did you know that you can publish one post and give it an expiration date? The posts don’t have to be displayed on the page forever – they can vanish whenever you want them to. Here is what you do.
Edit the theme you are using. Replace the loop you have already with this code:
<?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
$expirationtime = get_post_custom_values(‘XX/XX/XXXX XX:XX’);
if (is_array($expirationtime)) {
$expirestring = implode($expirationtime);
}
$secondsbetween = strtotime($expirestring)-time();
if ( $secondsbetween > 0 ) {
// For example…
the_title();
the_excerpt();
}
endwhile;
endif;
?>
You should know that by using this code, you are not un-publishing or removing a post you have created. All you are doing is removing it from the loop.
6. Find and Display a Post that Was Published One Year Ago
With so much content on your site, you probably don’t know where to start. But, you should definitely not top posting new content and re-using the past content. Many of your visitors haven’t seen your old content and will probably not attempt to find it by themselves.
Your job is to bring it back. i.e. add it to the loop by using this code in the blog sidebar:
<?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;
?>
7. Create Your Own Loop
You may want to create your own loop for many reasons. By using the classic one provided by WordPress, you risk offsetting, resetting issues, and many other problems. If you do decide to create your loop, here is the code you can use:
<?php
$myPosts = new WP_Query();
$myPosts->query(‘showposts=5’);
while ($myPosts->have_posts()) : $myPosts->the_post(); ?>
the_title();
the_content();
endwhile;
8. Create an Images Loop
Finally, we will help you post images the same way you post content and blog posts. Wouldn’t you like to create a kind of a ‘gallery loop’ where visitors can see the lead images of each post you have published? You don’t necessarily need custom fields for this – there is a much simpler way.
Just paste this code in the functions.php file and define the image:
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)){ // default image
$first_img = “/images/default.jpg”;
}
return $first_img;
}
Then, save the file and display the image by using this code:
<?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<a href=”<?php the_permalink();?>” title=”<?php the_title(); ?>” class=”img-loop”>
<img src=”https://www.smashingmagazine.com/wp-content/uploads/images/wordpress-loop-hacks/<?php echo catch_that_image() ?>” alt=”<?php the_title(); ?>” />
</a>
endif;
?>
That’s it! These 8 hacks should help you achieve a lot by doing simple copy-pasting on your WordPress site!
- 8 WordPress Loop Hacks - April 21, 2018