Search code examples
phphtmlwordpresspaginationposts

Custom category pagination Wordpress


I have a custom loop on a custom template page in WordPress that is showing posts from a particular category. This all works great and shows everything I need, however I need to add some pagination eventually. As this is a custom loop it seems that the native WP 'Blog pages show at most' does not work. Is there a way to add pagination to my custom loop?

   <?php
    // add journal posts to the journal page
    query_posts( array ( 'category_name' => 'journals', 'posts_per_page' => -1 ) );
    ?>
    <?php
    // The Loop
    while ( have_posts() ) : the_post();
        echo '<div class="journal-posts">';
        echo '<h2 class="entry-title">';
        echo '<div><a href="'. esc_url( get_permalink() ) . '">' . sprintf(__( get_the_title() )) . '</a> <img src="http://localhost/website.co.uk/wp-content/themes/themename/images/icons/icon.png" alt="Icon Stuff"/></div>';
        echo '</h2>';
        echo '<span class="entry-meta">Posted on ';
        echo '<span class="date-link">';
        the_date();
        echo '</span>';
        echo ' by ';
        echo '<span class="author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>';
        echo '</span>';
        the_content();
        echo '</div>';
        endwhile; ?>
  <?php
  // Reset Query
  wp_reset_query();
?>

I have three separate categories being called for this site hence why I need to have this custom loop on each of those pages. Unless there is a better way to do it?

Thanks in advance!


Solution

  • I think the key is setting up / using the $paged attribute within the query as follows:

    $paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
    $query_args = array(
      'post_type' => 'post',
      'category_name' => 'tutorials',
      'posts_per_page' => 5,
      'paged' => $paged
    );
    

    This is taken from and explained very well in this article and in this question.