Categories
CMS Mastering Development Wordpress

WordPress pagination problem on merged queries

I have merged queries in search.php with custom post types. This is my scenario when user search to "math", the main query is searching in the post title, post excerpt, and post content. Now I have a "math" category but the post information is not including "math" text which exists in the math category so it’s not showing in search results. I want to add it. I merged 2 queries and it’s working but pagination is going to 404 when search text is the only category name. If I search the post names pagination is working fine. Here are my code blocks

search.php

$term_ids=[];
$search_text_list = explode(" ", $s);

foreach($search_text_list as $search_text){
    $terms = get_terms('category', array(
        'name__like' => $s,
        'orderby'    => 'id',
        'hide_empty' => true
    ));
    if (count($terms) > 0){
        foreach($terms as $term){
            array_push($term_ids,$term->term_id);  
        } 
    }
}
if(count($term_ids) == 0){$term_ids[]=-1;}

$arg1 = array(  
    'post_type' => 'course',
    'fields' => 'ids',
    'post_status' => 'publish',
    's' => $s,
    'posts_per_page' => -1
);

$arg2 = array(  
    'post_type' => 'course',
    'post_status' => 'publish',
    'fields' => 'ids',
    'category__in' => $term_ids,
    'posts_per_page' => -1
);

$query1 = new WP_Query($arg1);
$query2 = new WP_Query($arg2);

$post_ids = array_merge($query1->posts, $query2->posts);
$post_ids = array_unique($post_ids);
$search_count = count($post_ids);
if($search_count == 0){$post_ids[] = -1;}

$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$argo = array(  
    'post_type' => 'course',
    'post__in' => $post_ids,
    'posts_per_page' => 2,
    'orderby' => 'ID',
    'order' => 'DESC',
    'paged' => $paged
);

$search_query = new WP_Query($argo);
$max_num = $search_query->max_num_pages;

if ($search_query->have_posts()) : while($search_query->have_posts()) :  $search_query->the_post();
echo get_the_title();
endwhile; 
else :
echo "not found";
endif;

$big = 999999999;
echo paginate_links( array(
  'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
  'format' => '?paged=%#%',
  'current' => max( 1, get_query_var('paged') ),
  'total' => $search_query->max_num_pages,
  'prev_text' => '< Prev',
  'next_text' => 'Next >'
));
wp_reset_postdata();

function.php

function fix_query_post_per_page($query){
    if ($query->is_main_query() && ! is_admin() && is_search()){
        $query->set( 'post_type', array( 'course' ) );
        $query->set( 'posts_per_page', '2' );
    }
}
add_action('pre_get_posts', 'fix_query_post_per_page');

So how can I fix this problem? Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *