Categories
Web Development WordPress

WordPress: Query Loop Syntax

This post is long overdue on this blog. I have personally used this method of querying and iterating through the results many many times. Below is the standard structure for a query and a loop. This query and loop will find all ‘post’s on this WordPress website that have the ‘people’ taxonomy with ‘bob’ checked off.

<?php
// define the search arguments
$args = array(
	'post_type' => 'post',
	'tax_query' => array(
		array(
			'taxonomy' => 'people',
			'field'    => 'slug',
			'terms'    => 'bob',
		),
	),
);

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
	echo '<ul>';
	while ( $the_query->have_posts() ) {
		$the_query->the_post();
		echo '<li>' . get_the_title() . '</li>';
	}
	echo '</ul>';
} else {
	// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

Leave a Reply