-
-
Notifications
You must be signed in to change notification settings - Fork 95
Query vars for sorting
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.
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',
) );
Sort posts by their meta value by using the meta_key
parameter:
'foo' => array(
'meta_key' => 'foo',
),
Sort posts by their taxonomy term(s) by using the taxonomy
parameter:
'genre' => array(
'taxonomy' => 'genre',
),
Sort posts by any available post field by using the post_field
parameter:
'updated' => array(
'post_field' => 'post_modified_gmt',
),
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',
),