Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

How to add pagination to this query on search.php? WordPress

  • SOLVED

This code is for search.php. The code works fine, however I need to add pagination to the page, so that if more than 3 results are found they are shown on the next page. How can I do this please?



if ( have_posts() ) : ?>
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
<?php while ( have_posts() ) : the_post(); ?>
<a href="<?php echo get_permalink( ); ?>"><?php echo the_title(); ?></a>

<?php endwhile; ?>
<?php else : ?>
<p> there were no results </p>
<?php endif; ?>

Answers (2)

2015-06-05

Arnav Joy answers:

try this

if ( have_posts() ) : ?>

<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' ); ?></h1>

<?php while ( have_posts() ) : the_post(); ?>

<a href="<?php echo get_permalink( ); ?>"><?php echo the_title(); ?></a>



<?php endwhile; ?>
<nav class="navigation paging-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Posts navigation', 'aj' ); ?></h1>
<div class="nav-links">

<?php if ( get_next_posts_link() ) : ?>
<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', 'aj' ) ); ?></div>
<?php endif; ?>

<?php if ( get_previous_posts_link() ) : ?>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'aj' ) ); ?></div>
<?php endif; ?>

</div><!-- .nav-links -->
</nav>
<?php else : ?>

<p> there were no results </p>

<?php endif; ?>


Matthew Pollard comments:

Thanks, but that doesn't work. I don't see where it limits results to 3 per a page? I am looking for pagination.


Arnav Joy comments:

write following to functions.php

function aj_modify_posts_per_page( $query ) {
if ( $query->is_search() ) {
$query->set( 'posts_per_page', '3' );
}
}
add_action( 'pre_get_posts', 'aj_modify_posts_per_page' );

2015-06-05

Dbranes answers:

Just use the <em>the_posts_pagination()</em> function:

[[LINK href="http://codex.wordpress.org/Function_Reference/the_posts_pagination"]]http://codex.wordpress.org/Function_Reference/the_posts_pagination[[/LINK]]

Here's an example from the TwentyFifteen theme:

// Previous/next page navigation.
the_posts_pagination( array(
'prev_text' => __( 'Previous page', 'twentyfifteen' ),
'next_text' => __( 'Next page', 'twentyfifteen' ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>',
) );


To use 3 posts per page, you must use

'posts_per_page' => 3,


in your <em>pre_get_posts</em> hook callback (see your previous question).