Neatly Wrapping Custom Post Type Queries in a Custom Class that Extends WP_Query

Let’s say you have a custom post type book that you almost always want to order by title. In other words, when querying for books, the default should be to order them by title. Also, you would almost never use paging. Instead of repeating these query arguments over and over, you can wrap them in a class that extends WP_Query.

class My_Book_Query extends WP_Query {

	function __construct( $args = array() ) {

		$args = wp_parse_args( $args, array(
			'post_type' => 'book',
			'orderby' => 'title',
			'order' => 'ASC',
			// Turn off paging
			'posts_per_page' => -1,
			// Since, we won't be paging,
			// no need to count rows
			'no_found_rows' => true
		) );

		parent::__construct( $args );

	}
}

Then when querying for books, simply call this new class instead of WP_Query. And feel free to use any query arguments you normally would.

$r = new My_Book_Query( array(
	'order' => 'DESC'
) );

while ( $r->have_posts() ) {
	$r->the_post();
	the_title();
	echo '<br />';
}

wp_reset_postdata();

You could also add methods to the class and hook them up to WP_Query filters like posts_where, posts_join, etc. All nicely wrapped up in a class.

Update: I’ve expanded on this and posted a longer, more involved example on my blog. Check it out ».

About

Founder of Delicious Brains, the company behind the WP Migrate DB Pro plugin.

One thought on “Neatly Wrapping Custom Post Type Queries in a Custom Class that Extends WP_Query

Leave a Reply

Your email address will not be published. Required fields are marked *