I have a website that has been utilizing the WordPress REST API V2 plugin. I used the code below to add an extra argument (filter) that I could utilize when calling for posts that were tagged using the custom taxonomy topics
. The site needed the ability to add multiple taxonomy terms into the query and display any posts that had any of those terms that were specified, but only posts that had one of those terms specified.
add_action( 'rest_query_vars', 'custom_multiple_topics' );
function custom_multiple_topics( $vars ) {
array_push( $vars, 'tax_query' );
return $vars;
}
add_action( 'rest_post_query', 'custom_topic_query', 10, 2 );
function custom_topic_query( $args, $request ) {
if ( isset($args[ 'topics' ]) ) {
$pre_tax_query = array(
'relation' => 'OR'
);
$topics = explode( ',', $args['topics'] ); // NOTE: Assumes comma separated taxonomies
for ( $i = 0; $i < count( $topics ); $i++) {
array_push( $pre_tax_query, array(
'taxonomy' => 'topic',
'field' => 'slug',
'terms' => array( $topics[ $i ] )
));
}
$tax_query = array(
'relation' => 'AND',
$pre_tax_query
);
unset( $args[ 'topics' ] ); // We are replacing with our tax_query
$args[ 'tax_query' ] = $tax_query;
}
} // end function
An example API call would be something like this: http://example.com/wp-json/wp/v2/posts?per_page=10&page=1&filter[topics]=audit,data
This all worked great until updating to WordPress 4.7. After the updates these arguments are ignored. I am not sure where to start to fix this problem. There are no errors PHP or Javascript on the site, the custom filter is simply ignored. After the update all posts are displayed using this query regardless of what they are tagged with.
Has anyone run into this issue with the update?
I found the solution to this issue. It turns out that the action rest_query_vars
is no longer used after the update.
The solution is simple enough. I had to update my code that is firing on the rest_post_query
action to test the $request
rather than the $args
.
Here is my solution that replaces all of the code in the question:
add_action( 'rest_post_query', 'custom_topic_query', 10, 2 );
function custom_topic_query( $args, $request ) {
if ( isset($request['filter']['topics']) ) {
$pre_tax_query = array(
'relation' => 'OR'
);
$topics = explode( ',', $request['filter']['topics'] ); // NOTE: Assumes comma separated taxonomies
for ( $i = 0; $i < count( $topics ); $i++) {
array_push( $pre_tax_query, array(
'taxonomy' => 'topic',
'field' => 'slug',
'terms' => array( $topics[ $i ] )
));
}
$tax_query = array(
'relation' => 'AND',
$pre_tax_query
);
$args[ 'tax_query' ] = $tax_query;
}
} // end function
Note that I replaced each $args[ 'topics' ]
with $request['filter']['topics']