Skip to content
wp-skills
Register
tools/wordpress-wp-query-loop-generator

WordPress Query Loop Generator

Build a secondary WP_Query and the loop that goes with it — filters, ordering, meta and working pagination, with the wp_reset_postdata() call that keeps the rest of the page correct.

Comma separated. One value emits a string, several emit an array.

-1 returns every match at once, which is how a template runs out of memory on a large site.

Skips this many posts. Does not combine with pagination — WordPress honours the offset and ignores the page.

Slug, not name — this is the category_name argument.

Left out for the EXISTS comparisons, which ask only whether the key is present.

Reads the page number the main query does not set for you, and prints paginate_links().

Faster, but makes pagination impossible — ignored while pagination is on.

snippet.php
$args = array(
	'post_type'           => 'post',
	'post_status'         => 'publish',
	'posts_per_page'      => 10,
	'orderby'             => 'date',
	'order'               => 'DESC',
	'ignore_sticky_posts' => true,
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
	echo '<ul>';

	while ( $query->have_posts() ) {
		$query->the_post();

		printf(
			'<li><a href="%s">%s</a></li>',
			esc_url( get_permalink() ),
			esc_html( get_the_title() )
		);
	}

	echo '</ul>';

	// Puts the global $post back to the main query's post, which the_post()
	// overwrote. Without this every template tag after the loop — the page
	// title, the comment template, anything calling get_the_ID() — reads the
	// last post looped over here instead.
	wp_reset_postdata();
} else {
	printf( '<p>%s</p>', esc_html__( 'Nothing found.', 'text-domain' ) );
}