[Resolved] using “post__in” with the $query_args for “wpv_filter_query” filter hook
This thread is resolved. Here is a description of the problem and solution.
Problem:
Client is using the wpv_filter_query hook to modify the Query Arguments before a View query is run, but it doesn't seem to be having any effect.
Solution:
The wpv_filter_query filter should be used with a priority of at least 99, or any changes made may be overwritten.
i have two post_types: 'course' and 'course-group' which course-groups are the children of courses
in a view of 'course-groups' i want to filter them by the post_title of parent 'course'
i'm doing this by a php code:
add_filter( 'wpv_filter_query', 'wpv_filter_query_callback' );
function wpv_filter_query_callback( $query_args ) {
$search_filters = false;
if( $query_args['post_type'][0] == 'course-group' ){
if( isset($_GET['course-name-for-course-group'])){
if(!isset($query_args['post__in']))
$query_args['post__in'] = array();
$search_filters = true;
$args = array(
'post_type' => 'u_course',
's' => sanitize_text_field($_GET['course-name-for-course-group']),
'fields' => 'ids'
);
$posts = get_posts( $args );
foreach ($posts as $item){
$course_groups = toolset_get_related_posts(
$item, // get posts related to this one
'u_course-course-group', // relationship between the posts
'parent', // get posts where $writer is the parent in given relationship
100, 0, // pagination
array( ), // How was his surname, again…?
'post_id'
);
log_status($item);
log_status(serialize($course_groups));
foreach ($course_groups as $value)
if(!in_array($value , $query_args['post__in']))
array_push($query_args['post__in'] , (int)$value);
}
}
}
log_status(serialize($query_args));
return $query_args;
}
the "log_status" function, logs sth in a file "log.txt"
and the screenshot is the result of $query_args before returning it
the ids are correct but the view shows all of the course-groups
Without look too closely at your code, I think the issue is the priority with which you are using the wpv_filter_query filter.
By not specifying a priority you are defaulting to 10.
Officially it needs to be 99 to avoid the possibility of any of your changes to $view_args being overwritten, and in practice I always use 101, e.g. here is my boilerplate:
function tsupp_custom_query( $view_args, $view_settings, $view_id ){
if ( in_array( $view_id, array( 66, 77 ) ) ) { // Edit for View IDs
// do stuff
}
return $view_args;
}
add_filter( 'wpv_filter_query', 'tssupp_custom_query', 101, 3 );