Makers Byte
Published in

Makers Byte

Mastering Query Loops for WordPress

Using the WP_Query

via Google Images

Without a loop, nothing will be displayed on your page. After WordPress has run the query, using the arguments you’ve defined, it then needs to be told what to output from the data that it’s fetched. This is where the loop comes in.

So the loop comes after your query, and it uses three tags:

  • if( $query->have_posts() ) checks if there are any posts.
  • while( $query->have_posts() ) repeats the loop for each post as long as there are posts to retrieve.
  • $query->the_post() accesses that specific post.

So this is where the loop fits in the WP_Query class:

<?php // Arguments for your query.$args = array();
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) { $query->the_post();// Contents of the queried post results go here.}}// Restore original post data.wp_reset_postdata();?>

After running the loop, all that’s left to do is tidy things up using wp_reset_postdata().

Structure of the Loop

The way your loop is structured will depend on what data you want to display from your post. Here’s an example loop which outputs the post title, featured image and an excerpt. You’d use a loop like this on an archive page.

<?php// Arguments for your query.$args = array();// Custom query.$query = new WP_Query( $args );// Check that we have query results.if ( $query->have_posts() ) {// Start looping over the query results.while ( $query->have_posts() ) { $query->the_post(); ?><article id="post-<?php the_ID(); ?>" <?php post_class( 'left' ); ?>><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php post_thumbnail( 'thumbnail' );?></a><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><?php the_excerpt(); ?></article><?php}}// Restore original post data.wp_reset_postdata();?>

The loop initiate with the logic to first check whether the loop belongs to a single page or listing page. If the loop belongs to the listing page then it will list all the items in the blog and if it is a single page then it will just display post. If no post is available then loop has the option to display a custom message or a 404 page as per your need.

Thanks to WordPress templates, the loop can be customized for just about every page or type of content on your site. Here are few example snippets that can help:

Simple Query Loop for displaying blog list with title and excerpt:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?><h2><?php the_title() ;?></h2>
<?php the_excerpt(); ?>
<?php endwhile; else: ?><p>Sorry, no posts to list</p><?php endif; ?>

Query Loop for displaying blog list with title and content:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?><h2><?php the_title() ;?></h2>
<?php the_content(); ?>
<?php endwhile; else: ?><p>Sorry, no posts to list</p><?php endif; ?>

Query Loop for displaying single page with title and content:

As mentioned earlier that the loop very much remain same for the single page, so similar code can be used for displaying the post over a single page.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?><h2><?php the_title() ;?></h2>
<?php the_content(); ?>
<?php endwhile; else: ?><p>Sorry, no posts to list</p><?php endif; ?>

Basic Query Loop with Pagination:

<?phpglobal $wp_query;
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array( 'post_type' => 'posts','posts_per_page' => 6,'paged' => $paged) ;
query_posts( $args );
while ( have_posts() ) : the_post();
echo '<li>'; the_title();echo '</li>';endwhile;?>

Using Query Loop to filter custom taxonomies in custom post type:

<?phpquery_posts( array(
'post_type' => 'myportfoliotype',
'paged' => $paged,
'posts_per_page' => 80,
'tax_query' => array(
array(
'taxonomy' => 'category', //or tag or custom taxonomy
'field' => 'id',
'terms' => array('9')
)
)
)
);
?>

Using Query Loop with Advanced Custom fields:

<?php
query_posts( array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'event_id',
'value' => '1',
'compare' => '=',
)
)
));
?>

Using Single Custom field with advance custom fields for querying:

<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'event',
'meta_key' => 'location',
'meta_value' => 'Melbourne'
);
// query
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<img src="<?php the_field('event_thumbnail'); ?>" />
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>

Without a loop, WP_Query doesn't really do very much. The loop is the code you use to display the data that WordPress has fetched from the database based on your query arguments.

Did we missed anything, if so leave it as a comment :)

If you enjoyed this post…it would mean a lot to me if you could click on the “claps” icon…up to 50 claps allowed — Thank You!

--

--

--

Resource hub for Designers/Developers

Recommended from Medium

STAR INTERVIEW TECHNIQUE

Safely Keep Your Application Secrets in Repos Even if They’re Public Using Git-Crypt

Various colored plants in white pots

Decriminalization web OEM form 😂🤣 CI4 tag — this title came into my head blogging this article…

Resurfacing notes

Creating a Transparent Material in Unity

Code Smell 31 — Accidental Methods on Business Objects

Create hello world REST API

Introducing Cerberus: Software Testing Automation from Digital players, accelerated by open-source.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shahzaib Khan

Shahzaib Khan

Data Scientist, Developer, Tech Writer, Entrepreneur and Computer Science Enthusiast. Connect at https://www.linkedin.com/in/shahzaibkhan/

More from Medium

How to easily export and import WordPress Sites?

Rendering Contentful Rich Text Components in Gatsby

How to write alt texts for images?

Firebase 9 Vs 8: Compare Cloud Firestore CRUD Queries