Custom WordPress Loop

Posted on Nov 18, 2024

by Jimmy

Last updated on March 7, 2025


How to create a WordPress custom loop. Useful when needing to query specific data.

The Arguments

First we need to declare the arguments for the loop. Here is a full list of all the possible arguments from Bill Erickson.

PHP
        
            $args = array(
    'posts_per_page' => get_option('posts_per_page'),
    'post_type' => 'project', // <-- the name of your custom post type
    'post_status' => 'published'
);        
    

The Loop

Next we loop through the posts that we want to show based on the arguments we declared above.

PHP
        
            <?php 
$query = new WP_Query($args);

if ( $query->have_posts() ) :

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

        <?php get_template_part('inc/card-content'); ?>

    <?php endwhile; ?>

<?php else : ?>

    <p>Sorry, there are no projects to show at this time.</p>

<?php endif; wp_reset_postdata(); ?>        
    

Note

Make sure to add wp_reset_postdata(); right after the last if statement to return the $post global to the current post in the main query.

HTML
        
            <input type="text" name="email" disabled="disabled" />
<input type='text' name='email' disabled='disabled' />        
    

Back to Snippets