Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add custom post types to search results in WordPress.
<?php
add_filter( 'pre_get_posts', 'tgm_io_cpt_search' );
/**
* This function modifies the main WordPress query to include an array of
* post types instead of the default 'post' post type.
*
* @param object $query The original query.
* @return object $query The amended query.
*/
function tgm_io_cpt_search( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'post', 'movies', 'products', 'portfolio' ) );
}
return $query;
}
@RyuuZaky

This comment has been minimized.

Copy link

RyuuZaky commented Oct 21, 2016

Just found this, thank you a lot !

@aligator28

This comment has been minimized.

Copy link

aligator28 commented Mar 13, 2017

Be carefuel to use this code example!
It makes VERY FRUSTRAITING BUG on admin page. I've spent 2 days to find it.
When you are on admin page this function doesn't allow you to filter custom post types and woocommerce products on categories, dates etc..
Better change 12th line of code in such way:
12. if ( $query->is_search && !is_admin() ) { .....
Just check if you are not on admin dashboard...

@kevinee007

This comment has been minimized.

Copy link

kevinee007 commented Aug 7, 2017

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.