WordPress.org

Ready to get started?Download WordPress

Forums

Adding pagination to a custom theme (6 posts)

  1. cerics
    Member
    Posted 11 months ago #

    I've built a custom theme and I would like to add pagination to it.

    In my search.php file I have this loop set up:

    <?php $search_count = 0;
    	$search = new WP_Query("s=$s & showposts=-1");
    	if($search->have_posts()) : while($search->have_posts()) : $search->the_post();
    	$search_count++; endwhile; endif; echo $search_count;?> results for '<?php the_search_query(); ?>'
    </h4>
    <ol class="search-result">
    <?php if(have_posts()) : while(have_posts()) : the_post(); ?>
    <li>
    <a href="<?php the_permalink(); ?>"><span class="the-title"><?php the_title(); ?></span>
    <span class="the-exerpt"><?php the_excerpt(); ?></span>
    <span class="the-permalink"><?php the_permalink(); ?></span></a>
    </li>
    <?php endwhile; endif; ?>

    How can I add pagination to this?

  2. keesiemeijer
    moderator
    Posted 11 months ago #

  3. cerics
    Member
    Posted 11 months ago #

    I appreicate the help but I'm not sure how to implement these into my loop. I've never messed with pagination before.

  4. keesiemeijer
    moderator
    Posted 11 months ago #

    In the arguments you have 'showposts=-1'. This shows all search results (no pagination needed).
    Try it without the query in the search template and with the pagination functions (borrowed from twentytwelve):

    <?php if ( have_posts() ) : ?>
    <?php
    global $wp_query;
    if(isset($wp_query->found_posts) && $wp_query->found_posts){
    echo '<h4>' . $wp_query->found_posts . " results for '" . get_search_query() . "'</h4>";
    }
    ?>
    
    <ol class="search-result">
    <?php while ( have_posts() ) : the_post(); ?>
    <li>
    <a href="<?php the_permalink(); ?>"><span class="the-title"><?php the_title(); ?></span>
    <span class="the-exerpt"><?php the_excerpt(); ?></span>
    <span class="the-permalink"><?php the_permalink(); ?></span></a>
    </li>
    <?php endwhile; ?>
    </ol>
    <div class="nav-previous alignleft"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', 'twentytwelve' ) ); ?></div>
    			<div class="nav-next alignright"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?></div>
    <?php endif; ?>

    And set how many results you want in your theme's functions.php:

    add_action( 'pre_get_posts', 'search_query' );
    function search_query( $query ) {
    	if ( !is_admin() && $query->is_main_query() ) {
    		if ( is_search() ) {
    			// show 4 posts
    			$query->set( 'posts_per_page', 4 );
    		}
    	}
    }
  5. cerics
    Member
    Posted 11 months ago #

    Amazing! I have been trying to do this for months. Thanks keesiemeijer.

  6. cerics
    Member
    Posted 11 months ago #

    Any way to number these things?

Reply

You must log in to post.

About this Topic