Skip to content

Query vars for sorting

John Blackbourn edited this page Jun 4, 2015 · 2 revisions

Extended CPTs provides a mechanism for registering values for the public orderby query var, which allows users to sort your post type archives by various fields. This also works in WP_Query, which makes ordering custom post type listings very powerful and dead easy.

Think of these as the front-end equivalent of sortable columns in the admin area, minus the UI.

The array keys in the site_sortables array are used for the orderby value, which is my_foo and my_genre in the example below.

Example

register_extended_post_type( 'article', array(

	'site_sortables' => array(
		'my_foo' => array(
			'meta_key' => 'foo'
		),
		'my_genre' => array(
			'taxonomy' => 'genre'
		),
	),

) );

This allows your post type archive to be ordered thusly:

example.com/articles/?orderby=my_foo&order=asc

It also allows you to order posts in WP_Query thusly:

new WP_Query( array(
	'post_type' => 'article',
	'orderby'   => 'my_genre',
	'order'     => 'DESC',
) );

Available Sortable Fields

Post Meta Field

Sort posts by their meta value by using the meta_key parameter:

'foo' => array(
	'meta_key' => 'foo',
),

Taxonomy Term(s)

Sort posts by their taxonomy term(s) by using the taxonomy parameter:

'genre' => array(
	'taxonomy' => 'genre',
),

Post Field

Sort posts by any available post field by using the post_field parameter:

'updated' => array(
	'post_field' => 'post_modified_gmt',
),

Default Sort Field

Any field can be made the default sort field by using the default parameter and giving it a value of ASC or DESC:

'start_date' => array(
	'meta_key' => 'start_date',
	'default'  => 'DESC',
),