Creating custom post loops for WordPress

Posted on 7th January, 2016 455 Comments

So I know this has a ton of coverage on Google, but I thought I would add my own post on the subject as I use this blog as my own reference (which is the entire reason I created this site) with a few examples.

Let me give you a quick breakdown of how a custom loop works.

  1. You would generally start off with your arguments for the loop.
    A full list of arguments can be seen here https://gist.github.com/luetkemj/2023628
  2. Then create a new WP_Query and assign the arguments to it.
    https://codex.wordpress.org/Class_Reference/WP_Query
  3. Which is then used to check and display your posts.

You can control all kinds of things with a custom post loop, most recently I had to create 3 loops for a single blog page.
The first loop I needed was to only grab the sticky posts which were under a particular category “alerts”.

Example below:

<?php 
$sticky = get_option( 'sticky_posts' ); /* GRAB THE STICKY POST OPTION */
if (is_front_page() && $sticky) {
$args = array(
	  'post__in'			=> $sticky,
	  'posts_per_page'		=> 5, /* SHOW A MAXIMUM 5 POSTS */
	  'category_name'		=> 'alert', /* IF THEY ARE IN THE CATEGORY "ALERT" */
	  'no_found_rows'		=> true,
	  'ignore_sticky_posts' => 1
	);	
	
$sticky_query = new WP_Query($args); /* SET THE NEW QUERY WITH THE ABOVE ARGS */
?>	

<?php if ( $sticky_query->have_posts() ) { /* CHECK THE ARGUMENTS AGAINST THE POSTS */ ?>
			<div id="alert">
				<div class="wrapper">
					<div class="close"><i class="fa fa-times"></i></div>
					<div class="ticker">
						<ul>
			<?php while ( $sticky_query->have_posts() ) : $sticky_query->the_post(); /* FINALLY OUTPUT THE CUSTOM LOOP */ ?>
						<li>
						<strong><?php the_title(); ?> - </strong>
						<?php the_excerpt(); ?>
						</li>
			<?php endwhile; ?>
						</ul>
					</div>
				</div>
			</div>
<?php  wp_reset_postdata(); } } /* MAKE SURE YOU RESET YOUR LOOP! */ ?>	

The second loop I used was to grab only the first most recent post from the blog as I had set a featured/larger post section to display this.

<?php if(have_posts()) :?>
	
	  <?php
          $args = array('posts_per_page' => 1);  /* GRAB ONLY THE FIRST POST */
          $loop = new WP_Query( $args );
          while ( $loop->have_posts() ) : $loop->the_post(); ?>
		
		<div class="first-post clearfix">
			<article>
				<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
				<p><small>Published <?php the_time('M jS, Y'); ?> by <?php the_author(); ?></small></p>
				<p><?php $content = get_the_content(); 
						echo wp_trim_words($content, '30', '... '); ?></p>
                <a href="<?php the_permalink(); ?>" class="readmore">Read More</a>
			</article>
            <a href="<?php the_permalink(); ?>">
			<?php if (has_post_thumbnail()) {
						if ( strlen( $img = get_the_post_thumbnail( get_the_ID(), array( 150, 150 ) ) ) ) {
							echo get_the_post_thumbnail($post->ID, 'blog-feature');
						} else {
							 echo '<img src="' . get_bloginfo('template_directory') . '/images/blog/default-blog-feature.jpg" />';
						}					  
					} else {
					   echo '<img src="' . get_bloginfo('template_directory') . '/images/blog/default-blog-feature.jpg" />';
					} ?></a>
		</div><!-- /.first-post -->
	<?php endwhile; wp_reset_postdata(); ?>

The third loop was to just show the rest of the blog posts as normal, but making sure that I didn’t show the first post OR keep the sticky post at the top of the articles.

<div class="posts">
			 <?php
			  $args2 = array(
			  			'offset' => 1, /* REMOVE THE FIRST POST FROM THIS LOOP */
						'ignore_sticky_posts' => 1 /* IGNORE THE STICKY POSTS "STICK-ABILITY" */
						);  
			  $loop2 = new WP_Query( $args2 );
			  while ( $loop2->have_posts() ) : $loop2->the_post(); ?>
				<div class="single clearfix">
					<a href="<?php the_permalink(); ?>">
					 <?php if (has_post_thumbnail()) {
								if ( strlen( $img = get_the_post_thumbnail( get_the_ID(), array( 150, 150 ) ) ) ) {
									echo get_the_post_thumbnail($post->ID, 'blog-icon');
								} else {   
									echo '<img src="' . get_bloginfo('template_directory') . '/images/blog/default-blog-icon.jpg" />';
								}
							} else {
							   echo '<img src="' . get_bloginfo('template_directory') . '/images/blog/default-blog-icon.jpg" />';
							} ?></a>
					<article>
						<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
						<p><small>Published <?php the_time('M jS, Y'); ?> by <?php the_author(); ?></small></p>
						<a href="<?php the_permalink(); ?>" class="readmore">Read More</a>
					</article>
				</div>		
						
			<?php endwhile;  wp_reset_postdata(); ?>
</div> <!-- /.posts -->

Lastly, if you’re using pagination on your posts you’ll find that you’ll need a new loop when your paging.
So you will need to create a fourth loop and wrap the above loop in a controlling if statement.

	
		<div class="posts">
		<?php if(!is_paged()) { /* CHECK IF WE'RE ON PAGE 1 OF THE POSTS */ ?> 
			 <?php
			  $args2 = array(
			  			'offset' => 1,
						'ignore_sticky_posts' => 1
						);  
			  $loop2 = new WP_Query( $args2 );
			  while ( $loop2->have_posts() ) : $loop2->the_post(); ?>
				<div class="single clearfix">
					<a href="<?php the_permalink(); ?>">
					 <?php if (has_post_thumbnail()) {
								if ( strlen( $img = get_the_post_thumbnail( get_the_ID(), array( 150, 150 ) ) ) ) {
									echo get_the_post_thumbnail($post->ID, 'blog-icon');
								} else {   
									echo '<img src="' . get_bloginfo('template_directory') . '/images/blog/default-blog-icon.jpg" />';
								}
							} else {
							   echo '<img src="' . get_bloginfo('template_directory') . '/images/blog/default-blog-icon.jpg" />';
							} ?></a>
					<article>
						<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
						<p><small>Published <?php the_time('M jS, Y'); ?> by <?php the_author(); ?></small></p>
						<a href="<?php the_permalink(); ?>" class="readmore">Read More</a>
					</article>
				</div>		
						
			<?php endwhile;  wp_reset_postdata(); ?>

		<?php } else { // OTHERWISE WE'LL USE THE STANDARD LOOP... ?>
		
			<?php while ( have_posts() ) : the_post(); ?>
			<div class="single clearfix">
                <a href="<?php the_permalink(); ?>">
				 <?php if (has_post_thumbnail()) {
							if ( strlen( $img = get_the_post_thumbnail( get_the_ID(), array( 150, 150 ) ) ) ) {
								echo get_the_post_thumbnail($post->ID, 'blog-icon');
							} else {   
								echo '<img src="' . get_bloginfo('template_directory') . '/images/blog/default-blog-icon.jpg" />';
							}
						} else {
						   echo '<img src="' . get_bloginfo('template_directory') . '/images/blog/default-blog-icon.jpg" />';
						} ?></a>
				<article>
					<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
					<p><small>Published <?php the_time('M jS, Y'); ?> by <?php the_author(); ?></small></p>
                    <a href="<?php the_permalink(); ?>" class="readmore">Read More</a>
				</article>
            </div>	
		
		<?php endwhile; } //is_paged() end ?>
		<?php endif; ?>	
			
			<?php post_pagination(); ?>
			
		</div> <!-- /.posts -->

Comments

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]

VictorAmisp

17th, Oct, 20

curiosity a case fatality of wet soluble with tumeric or. cialis and suggestion some on the chance with a medicament accumulation.

JamesVen

21st, Oct, 20

amount that can chore to boldness may or other groups. [url=https://ciamedusa.com/]cialis dose[/url] therapy the forbearing or the manual of the colon cancer.

JamesVen

25th, Oct, 20

any other placenta; in search the People is no brittle [url=https://ciamedusa.com/]cialis pills[/url] Rywhnn fucxhc

Dencar

08th, Dec, 20

[url=http://viagranova.com/]can you purchase viagra over the counter[/url] [url=http://cialisely.com/]buy generic cialis online safely[/url] [url=http://lyricapill.com/]lyrica 75 mg price south africa[/url] [url=http://bloodpressuremed.com/]buy avalide[/url] [url=http://buyhydroxychloroquineplaquenil.com/]buy plaquenil uk[/url]

Hydraruzxpngake

23rd, Dec, 20

hydraruzxpnew4af.union что это за сайт – это хорошый магазин теневых товаров. Для совершения покупок на анонимной платформе гидра наш вэб-портал в любой день обслуживает большое количество юзеров, для входа надо нажать на кнопку и конфиденциально совершить покупку, а в случае если Вы в 1-ый раз зашли на магазин перед покупкой товара надо зарегистрироваться и пополнить счет. Ваша защищенность наша значимая задача, которую мы с удовольствием исполняем.

zortilonrel

25th, Dec, 20

Does your website have a contact page? I’m having a tough time locating it but, I’d like to shoot you an email. I’ve got some ideas for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it expand over time.

Hydrasajtgake

25th, Dec, 20

ссылка онион гидра являет собой платформер, который рассчитан для дилеров запрещенных вещей и спецуслуг. Подобную продукцию неприлично взять в традиционном магазине, так как это неправомерно.

hey

05th, Jan, 21

Taxi moto line
128 Rue la Boétie
75008 Paris
+33 6 51 612 712  

Taxi moto paris

Howdy just wanted to give you a quick heads up.
The words in your content seem to be running off the screen in Chrome.
I’m not sure if this is a formatting issue or something to do with browser compatibility but
I figured I’d post to let you know. The style and design look
great though! Hope you get the problem resolved soon. Many thanks

JamesRow

15th, Jan, 21

generic cialis coming out cialis bivamkbp how much does cialis cost at walmart

KbbgBoth

29th, Jan, 21

gdzie kupiД‡ viagra Lasix levitra vs viagra side effects [url=http://erectilejyzd.com/]pharmeasy[/url] ’

gidrasajt4afgake

02nd, Feb, 21

gidrasajt4af.com похожа на портал, что предназначен для дилеров подпольных изделий и услуг. Такую же продукцию запрещается достать в обычном интернет-магазине, так как это противозаконно.

anderson149.ljdatmuahangmy.com/p/1

18th, Feb, 21

We’re a bunch of volunteers and starting a new scheme in our community.
Your site offered us with helpful info to work on. You
have done a formidable task and our entire community shall be thankful to you.

우리카지노

19th, Feb, 21

Good day! I just would like to offer you a big thumbs up for your great info you have got here on this post.
I’ll be returning to your blog for more soon.

pinupcasinoo

23rd, Feb, 21

Игровые автоматы в Украине это [url=https://pin-up-casino999.ru/]Pin Up[/url] Casino, играть можно на деньги, а можно бесплатно. Стабильно выплачивают выигрыши без задержек. РЕКОМЕНДУЮ!

froleprotrem

25th, Feb, 21

We are a bunch of volunteers and opening a brand new scheme in our community. Your site provided us with valuable info to paintings on. You’ve done an impressive activity and our entire neighborhood will be thankful to you.

Howardhum

20th, Mar, 21

dating seiten
[url=”http://freedatingsitesus.com/?”]chat websites to meet people [/url]

HaroldMek

29th, Mar, 21

The Best Places To Day Hookup Females

The number of hookup girls for just one person is normally small, and this means whenever you hire a company who is really like yourself in all regards, chances are quite high that they are also probably going to be an effective match up to suit your needs [url=https://wikihookup.com/2006-yamaha-225-outboard-digital-guage-hookup]https://wikihookup.com/2006-yamaha-225-outboard-digital-guage-hookup[/url] Imagine if you don’t have very much good fortune with internet hookups? Properly, there are additional techniques that you can approach discovering somebody to hookup with. While these methods may not be as quickly as making use of internet dating, they may be less complicated and therefore are often more affordable, which definitely ensures they are a workable option.

Free of charge Hookup Women: Something that can be done is always to appear on the web for any free dating website. These internet sites are strictly for single men and women, but there are many sites that cater to couples or relationships at the same time. While they are certainly not specifically designed for hookups, you may still find some very good options at totally free hookups. This may not be an ideal way for you to fulfill a hookup, but it may be a good strategy for finding out if this type of individual is somebody that you would probably feel at ease with dating or connecting with on a much more long lasting time frame.

Paid out Dating Providers: There are on-line services like hookup colder and Zoosk that happen to be cost-free to enroll in. They already have both compensated and totally free models, and each of them their very own very own advantages. A number of the advantages of a paid out service consist of the fact that you know precisely what you really are engaging in before you even sign in to your bank account, which means you might have additional control over the condition, and when you purchase not to complement it, you can stop at any time.

Live On-line Hookups: There are actually numerous countries where on-line hookup solutions are common. India is among these countries. In India, numerous teenagers, particularly individual ladies, will leverage the internet to locate an individual to get a one particular night remain with. In lots of elements of Asia, men and women will head to karaoke pubs and public dances and then try to fulfill a person for a date. There is lots of sex concerned and it is perfectly appropriate in lots of Asian cultures.

In the usa, hookup online dating services are becoming more popular. This is because they supply a good way for folks from all of avenues of life to find a person to particular date. As many dating sites fee a small monthly fee, there is no reason why anyone that is interested in finding someone should struggle to do so on the Internet at no cost. It is actually less hazardous than getting together with personally, and yes it enables you to stay in the personal privacy of your personal home. With one of these professional services, you can actually browse through user profiles and discover if you have anyone that you are currently drawn to.

Transunion: As stated before, hookup courting on the web has its disadvantages. The downfall of it is it is incredibly easy to rest about your grow older, earnings, or marital standing. Because of this, you could possibly wind up shelling out weeks seeking to find the best go with. One of the better services for finding complements for queers is TransUnion. The best thing about it is you can get credit report checks, pay very little, and perhaps you will definitely get immediate credit rating acceptance.

I would personally definitely propose these three providers as the easiest method to hookup with females. In the event you prefer to use cost-free online dating sites, make sure you shop around prior to signing up. Some websites are phony, deceptive, and will lead to harm to your upcoming. Remember to learn the privacy policy and policies of your site, and make sure the website has existed for a significant when. Every one of these factors will allow you to get the best support for your requirements.

Hookups with women is a great way to fulfill a fresh partner and expertise a fresh customs. If you are looking so far a lady on the internet, remember that there are numerous fraudulent online dating sites. The best recommendation is to look into the Much better Company Bureau before utilizing any online dating services professional services. It’s always advisable to be secure than sorry. Whether or not you opt to use online hookup solutions or otherwise not, there are many individuals out there who are trying to find a romantic relationship such as you.

강남안마

18th, Apr, 21

Great paintings! This is the type of information that are supposed to be shared around the web. Shame on the seek engines for now not positioning this post higher! Come on over and discuss with my web site . Thanks =)

Miles Fryday

25th, Apr, 21

Have you ever heard of second life (sl for short). It is basically a video game where you can do anything you want. sl is literally my second life (pun intended lol). If you want to see more you can see these Second Life authors and blogs

Archie Halling

26th, Apr, 21

Have you ever heard of second life (sl for short). It is basically a game where you can do anything you want. sl is literally my second life (pun intended lol). If you would like to see more you can see these second life articles and blogs

click here

28th, Apr, 21

Hello there! This is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your articles. Can you suggest any other blogs/websites/forums that cover the same topics? Thank you!

url

28th, Apr, 21

I have to show appreciation to this writer for rescuing me from this particular predicament. Because of exploring through the world-wide-web and getting basics that were not beneficial, I was thinking my entire life was well over. Living without the presence of approaches to the issues you have resolved by means of your main report is a crucial case, as well as ones that would have in a wrong way affected my entire career if I had not come across your web site. Your personal talents and kindness in controlling all the stuff was important. I don’t know what I would have done if I hadn’t encountered such a point like this. I can at this point relish my future. Thanks a lot very much for your impressive and amazing help. I won’t think twice to suggest the website to anyone who needs to have guide about this topic.

site

29th, Apr, 21

There is noticeably a bundle to realize about this. I assume you made certain good points in features also.

here

29th, Apr, 21

Very good written information. It will be supportive to everyone who utilizes it, including yours truly :). Keep doing what you are doing – can’r wait to read more posts.

url

29th, Apr, 21

I know this if off topic but I’m looking into starting my own blog and was curious what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet smart so I’m not 100 sure. Any recommendations or advice would be greatly appreciated. Kudos

site

29th, Apr, 21

I really like your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to design my own blog and would like to find out where u got this from. kudos

website

29th, Apr, 21

Perfect work you have done, this internet site is really cool with fantastic information.

Saniflo Macerator Pumps

02nd, May, 21

Nice read, I just passed this onto a colleague who was doing some research on that. And he just bought me lunch as I found it for him smile Therefore let me rephrase that: Thank you for lunch! “We have two ears and one mouth so that we can listen twice as much as we speak.” by Epictetus.

Saniflo Macerators

02nd, May, 21

I’m not that much of a online reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back down the road. Many thanks

web page

03rd, May, 21

I am extremely impressed together with your writing skills and also with the layout to your blog. Is that this a paid subject or did you customize it your self? Either way keep up the nice quality writing, it is rare to look a nice weblog like this one today..

loseweightbooks

03rd, May, 21

Appreciating the commitment you put into your site and detailed information you provide. It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed material. Excellent read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

gidrasteer_com_gake

04th, May, 21

Для Вашей анонимности наша команда сделали этот сайт на котором Вы изо дня в день сможете владеть доступом к магазину торговой площадки гидра hydraruzxpnew4af . Взять ссылку на hydra onion и безопасно сделать покупочку можно на просторах текущего блога. В интернет сети веб часто нарваться на преступников и упустить финансы.

usd to eur

04th, May, 21

I was reading through some of your blog posts on this site and I conceive this site is very informative ! Retain putting up.

zovirax dose for fever blister

07th, May, 21

What i don’t realize is in reality how you are not actually much more well-favored than you might be now.
You are very intelligent. You already know therefore significantly
in relation to this matter, produced me personally imagine it from
numerous varied angles. Its like men and women are not fascinated
unless it’s something to do with Woman gaga! Your own stuffs nice.

Always handle it up! http://herreramedical.org/acyclovir

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]