Bulding off of this response from @kaiser about being able to filter by post types on a search page, I wanted to be able to automatically add-in all of the public post types available. So, after some help with @kaiser, I came up with:
function sw_custom_post_type_includes($query) {
$args = array(
'public' => true
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types( $args, $output, $operator );
if ( !is_search() && !in_array( get_post_type(), $post_types ) )
return;
$query->set( 'post_type', $post_types );
return $query;
}
add_filter('pre_get_posts', 'sw_custom_post_type_includes');
Which initially seemed to work great, but I ran into an issue -> everything filtered by post type correctly EXCEPT when I tried to use &post_type=page
. I was actually getting an undefined index error for post_type
. I couldn't figure out why this wasn't working. So, I decided to use print_r($query->query_vars)
to see if everything was being pulled in correctly. Low and behold - for all post types EXCEPT for pages, that variable was set.
I conferred with another dev on this and they verified the issue. This is what I ended up using as a workaround:
function sw_custom_post_type_includes($query) {
if(isset($_GET['post_type']) && ((!isset($query->query_vars['post_type'])) || (isset($query->query_vars['post_type']) && $query->query_vars['post_type'] != 'nav_menu_item'))) {
$query->set('post_type', urldecode($_GET['post_type']));
}
}
add_action('pre_get_posts', 'sw_custom_post_type_includes');
This honestly seems like an odd workaround for something that has been baffling me for a few hours. Anyone with input on this will be rewarded with virtual high-fives.
$post_types
is the$args
array.var_dump()
of theglobal $wp_post_types
at the beginning of the function, please.