I am trying to filter a CPT by an array of post ids using pre_get_post filter within my plugin. Everything works fine when there are post that match the ids, but when there are no post that match the ids I am getting all the post within the CPT that I am trying to filter in return. What I need id there are not post ids found (or post from the post ids) is the archive page to display the normal 'no results found'.
This is a run down of my script...
add_action('pre_get_posts', array(__CLASS__, 'get_posts')); //run inside a class
function get_posts($wp_query) {
if ($wp_query->is_main_query() && !is_admin() && is_post_type_archive(MbeEnrollments::MBE_POST_TYPE_NAME) && $wp_query->query_vars['list-view'] == 'list-view') {
//For the purpose of this sample I removed the script in the section that produces the CPT post ids that I am trying to return. This portion works fine and as expected.
//if post ids are found
if ($post_ids) {
$wp_query->set('post__in', $post_ids);
}
return;
}
}
I assume the issue is that the CPT archive page will run as normal if my if($post_ids)
clause return false. However, I am trying to find a way to make it return with no results.
Thanks in advance for any help.
UPDATE: If I include a post id that I know does not exist within the CPT I get the desired 'No Results Found'. Even though this works it seems a little bit like a hack and there has to be a cleaner way. Any ideas? Here is the if that works....
if ($post_ids) {
$wp_query->set('post__in', $post_ids);
}else{//if no post ids then pass in a fake post id to get the 'no results found'
$wp_query->set('post__in', array(0));
}
return;
$post_ids
if there are no post IDs that match? An empty array?false
?null
? Something else?