0

I try to add a pagination system on my category.php page.

It works for the first page : for example url/category/cat1/. Good number of posts is displayed and I get a "read more" link only when it's needed...

But for the second page : for example url/category/cat1/page/2/. It doesn't load the code from category.php but from index.php !

What am I missing ?

Code from category.php :

<?php

get_header();

    $categories = get_the_category();

    if ( ! empty( $categories ) ) 
    {
        $category = $categories[0]->name;
    }
    $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;

    query_posts( 'category_name='.$category.'&posts_per_page=1&paged='.$paged );

    while (have_posts()) :

        the_post();
        the_title();
        the_excerpt();

        echo'<a href="'.get_permalink().'"> Read more...</a>';

    endwhile;

    ?>

     <div class="navigation">
     <div class="alignleft"><?php previous_posts_link('&laquo; Previous Entries') ?></div>
     <div class="alignright"><?php next_posts_link('Next Entries &raquo;','') ?></div>
     </div>

     <?php

get_footer();

 ?>

1 Answer 1

0

First off, don't use query_posts().

The current category will already be available to the category.php template.

To modify the category query and specify the number of posts per page to display, use the pre_get_posts hook and set the value of posts_per_page accordingly. The code below sets posts_per_page to 2. Add this code to you theme's functions.php file:

add_action( 'pre_get_posts', 'wpse_category_posts_per_page' );
function wpse_category_posts_per_page( $query ) {
    if ( is_admin() ) {
        return;
    }

    if ( $query->is_main_query() && $query->is_category() ) {
        $query->set( 'posts_per_page', 2 );
    }
}

Updated category.php template file:

<?php
/**
 * The category template.
 * 
 */
get_header();

if ( have_posts() ) :

    while ( have_posts() ) :
        the_post();
        the_title();
        the_excerpt();
        echo '<a href="' . esc_url( get_permalink() ) . '"> Read more...</a>';
    endwhile;

else :
    echo 'There are no posts in this category.';  
endif;
?>

<div class="navigation">
    <div class="alignleft"><?php previous_posts_link( '&laquo; Previous Entries' ) ?></div>
    <div class="alignright"><?php next_posts_link( 'Next Entries &raquo;','' ) ?></div>
</div>

<?php
get_footer();
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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