WordPress: Custom Loop Query
Creating a custom loop query can allow you to utilize the base WordPress loop with your own custom query. This could be used in many situations such as pulling only posts with a specific tag or pulling your own custom post types for displaying in a shortcode.
To utilize this you should have a basic knowledge of the WordPress loop.
First set up the arguments variable with the desired perimeters. For this example were going to request any post with the tag ‘cooking’.
1 2 3 4 5 |
// the query $args = array( 'post_type' => 'post', 'tag' => 'cooking' ); |
Now create a variable to hold your new results using the WP_Query class. Were going to pass are new arguments through the WP_Query’s first perimeter.
1 |
$the_query = new WP_Query( $args ); ?> |
From here we can use the WordPress loop as we normally would to cycle through the returned records. A full example can be found below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php // the query $args = array( 'post_type' => 'post', 'tag' => 'cooking' ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : ?> <!-- pagination here --> <!-- the loop --> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <h2><?php the_title(); ?></h2> <?php endwhile; ?> <!-- end of the loop --> <!-- pagination here --> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> |
More information on WP_Query including query perimeters can be found on the WordPress codex here.
Recent Comments