-
-
Notifications
You must be signed in to change notification settings - Fork 95
Query vars for filtering
Extended CPTs provides a mechanism for registering query vars which allow users to filter your post type archives by various fields. This also works in WP_Query
, which makes filtering custom post type listings very powerful and dead easy.
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/?foo=bar
It also allows you to filter posts in WP_Query
thusly:
new WP_Query( array(
'post_type' => 'article',
'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:
'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:
'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.
'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, regardless of its value (more specifically, if its value isn't empty-like, such as 0
or false
), by using the meta_exists
parameter:
'help_needed' => array(
'meta_exists' => 'help_needed'
),
Allow posts to be filtered by their taxonomy terms by using the taxonomy
parameter. Note that this is just a wrapper for WordPress' built-in taxonomy term filtering, because posts can be filtered by their taxonomy terms by default. Watch out for query var name clashes!
'genre' => array(
'taxonomy' => 'genre',
),
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',
),