0

I want search in specific multiple custom post types. I using second code to determine post types:

function custom_search_filter($query) {
    if ( !is_admin() && $query->is_main_query() ) {
        if ($query->is_search) {
              $query->set('post_type', array('post','product'));
        }
    }
}

add_action('pre_get_posts','custom_search_filter');

I can not search for woocommerce products, if in array post_type is more than only 'product' cpt. If is only 'product' then this post type is findable.

In my search.php file code is:

<?php if ( have_posts() ) : ?>
    <?php
    while ( have_posts() ) : the_post(); ?>
        founded 
    <? endwhile;
endif;
?>

If in array('post','page'), all is working good too, posts and pages are findable.

0

I recently had a similar problem and it had something to do with the query's posts_per_page parameter. Try setting it explicitly, like so:

function custom_search_filter($query) {
    if ( !is_admin() && $query->is_main_query() ) {
        if ($query->is_search) {
              $query->set('posts_per_page', 10 ); // Try setting it to the number you've set in the Wordpress admin (Settings > Reading). 
              $query->set('post_type', array('post','product'));
        }
    }
}

add_action('pre_get_posts','custom_search_filter');

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.