[wp-hackers] Include custom post type to search results

Frank Bueltge frank at bueltge.de
Mon Jan 28 08:16:30 UTC 2013


Hi Dmitry,
I think there is a good question for a open forum, like
http://wordpress.stackexchange.com/.
Is better to search about this topic for other users and maybe you get
earlier a answer.

But to your question.
I think the code to add the CPT to the search is right; only the hint,
exclude other conditionals, like preview or admin.
When init the function?Do you have the function and the add_filter() inside
a other function or method?

My example, works fine:
add_filter( 'pre_get_posts', 'fb_add_to_query' );
// ads to query function
fb_add_to_query( $query ) {

    if ( is_admin() || is_preview() )
       return;

    if ( ! isset( $query->query_vars['suppress_filters'] ) )
        $query->query_vars['suppress_filters'] = FALSE;

    // conditional tags for restrictions
    if ( $query->is_search && ( FALSE ==
$query->query_vars['suppress_filters'] ) )
        $query->set( 'post_type', array( 'post', 'recipes' ) );

    return $query;
}

Best


On Sun, Jan 27, 2013 at 11:57 PM, Dmitry Tokmakov <dmitry at getmoxied.net>wrote:

> Hi all,
>
> I'm experiencing the issue:
> I created custom post type "recipes", then I transferred some regular
> posts to new custom post type (just switched post type by looping through
> posts using wp_update_post()  ):
>
> -----------------------------
> $recipes = get_posts('post_type=post&cat=3&posts_per_page=-1');
>   foreach ($recipes as $recipe) {
>         $post_array = array(
>           'ID' => $recipe->ID,
>           'post_type' => 'recipes'
>         );
>         wp_update_post( $post_array );
>   }
> -----------------------------
>
>
> Then I added code below to functions.php to include custom post type in
> the search results, but it didn't make any difference - still no custom
> posts in the search results.
> -----------------------------
> function SearchFilter($query) {
>   if ($query->is_search) {
>     $query->set('post_type',array('recipes','post'));
>   }
>   return $query;
> }
> add_filter('pre_get_posts','SearchFilter');
> -----------------------------
>
>
> Any ideas ?
>
> Thank you in advance!
>
> Dmitry
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>


More information about the wp-hackers mailing list