How to add pagination in search results
Add this to your functions.php
file:
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('paged', ( get_query_var('paged') ) ? get_query_var('paged') : 1 );
$query->set('posts_per_page',6);
}
}
}
With which, you can actually set the number of posts per page.
user agent
With a strong foundation in object-oriented programming (OOP), I bring +4 years of professional experience as a Full Stack PHP developer, skilled in Laravel and VueJs frameworks for web development and API integration. I consistently keep myself up to date with the technologies I use as a developer and subscribe to the known relevant blogs in my field (Laravel News, Medium, VueJs.org, etc.), and to showcase my work, mainly built in Laravel and VueJs, I gradually update my GitHub. I consider myself a perpetual learner, and my passion is to use my skills and learnings to build solutions that create a significant impact on the lives of people around me.
Updated on June 04, 2022Comments
-
user agent almost 2 years
My search.php page looks like this:
get_header(); ?> <div class="search_result_page"> <section class="content-area"> <?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; if ( have_posts() ) : ?> <header class="results_heading"> <h6 class="rsults_title"><?php printf( esc_html__( 'Search Results for: %s', 'satsco' ), '<span class="search_query">' . get_search_query() . '</span>' ); ?></h6> </header><!-- .page-header --> <div id="result_search"> <?php /* Start the Loop */ while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content', 'search' ); endwhile;?> </div> <?php the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; ?> </section><!-- #primary --> </div> <?php get_footer();
Inside the while loop it calls another page called content-search which looks like this?
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?> <?php if ( 'post' === get_post_type() ) : ?> <?php endif; ?> </header><!-- .entry-header --> <div class="entry-summary"> <?php the_excerpt(); ?> </div><!-- .entry-summary --> </article><!-- #post-## -->
I just noticed now that when I search for "Where", it shows me all the posts that have the word Where.
So, how can I add pagination to it?
-
Luca Reghellin over 3 yearsThat's a function, I guess a callback. Which hook?
-
Luckyfella about 3 years@LucaReghellin It should be:
add_action( 'init', 'search_filter' );
I would recommend to set a prefix to the function name to avoid naming collisions -
Kristaps Folkmanis over 2 yearsI added this to the 'pre_get_posts' action. Otherwise there was an error.