-
-
Notifications
You must be signed in to change notification settings - Fork 96
Query vars for filtering
Extended CPTs provides a mechanism for registering public query vars which allow users to filter your post type archives by various fields. This also works in WP_Query
, although the main advantage is the fact these are public query vars accessible via URL parameters.
Think of these as the front-end equivalent of list table filters in the admin area, minus the UI.
The array keys in the site_filters
array are used as the names of the query vars, which is my_foo
and my_genre
in the example below. Be careful with query var name clashes!
register_extended_post_type( 'article', array(
'site_filters' => array(
'my_foo' => array(
'meta_key' => 'foo'
),
'my_genre' => array(
'taxonomy' => 'genre'
),
),
) );
This allows your post type archive to be filtered thusly:
example.com/articles/?my_foo=bar
It also allows you to filter posts in WP_Query
thusly:
new WP_Query( array(
'post_type' => 'article',
'my_foo' => 'bar',
) );
Allow posts to be filtered by an exact match on the value of the given meta key by using the meta_key
parameter:
'my_foo' => array(
'meta_key' => 'foo',
),
You can additionally specify a meta_query
parameter if your query var needs to provide a complex meta query filter, rather than just a match on the value. For example:
'my_foo' => array(
'meta_key' => 'foo',
'meta_query' => array(
'compare' => '>',
'type' => 'NUMERIC',
),
),
Allow posts to be filtered by a search on the value of the given meta key by using the meta_search_key
parameter. Uses a LIKE '%{value}%'
query in SQL.
'my_foo' => array(
'meta_search_key' => 'foo',
),
The meta_query
parameter documented above is also supported.
Allow posts to be filtered by posts which contain a meta field with the given meta key and a non-empty value, by using the meta_exists
parameter. This performs a NOT IN ( '', '0', 'false', 'null' )
query for the meta value.
'complete' => array(
'meta_exists' => 'complete'
),
Allow posts to be filtered by posts which contain a meta field with the given meta key, regardless of its value, by using the meta_key_exists
parameter. This performs an EXISTS
query for the meta key.
'help_needed' => array(
'meta_key_exists' => 'help_needed'
),
WordPress allows posts to be filtered by their taxonomy terms by default, so there's no need to implement a filter for taxonomy terms. Note that this does mean that you can't add filtering for a non-public taxonomy, but this isn't something I have plans to implement. PRs welcome if you do need this functionality.
Any filter can be restricted so it's only available to users with a given capability by using the cap
parameter:
'my_filter' => array(
'meta_key' => 'foo',
'cap' => 'manage_options',
),