WordPress.org

Ready to get started?Download WordPress

Forums

Pagination problem after adding query (3 posts)

  1. CissyH
    Member
    Posted 1 year ago #

    My client wants only the most recent blog to show on a specific category page, with sidebar links to older entries. I tried to handle this by adding a query to a custom category.php page (category-lakewatch.php) in my child theme. That worked fine as far as showing only one post, but then the "older posts" link at the bottom began returning a 404 message. I removed my customization and re-checked the page to make sure that was the cause of the error, and pagination worked fine without the query.

    My initial change to category-lakewatch.php was to add

    <?php query_posts( array ( 'category_name' => 'lakewatch', 'posts_per_page' => 1 ) ); ?>

    just before

    <?php if ( have_posts() ) : ?>

    on line 15 of category.php

    I read the documentation here which discussed pagination problems that could occur when adding a query then and tried these two suggested variations:

    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args = array(
    'category_name' => 'lakewatch', 'posts_per_page' => 1
      'paged' => $paged
    );
    ?>
    <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts( array ( 'category_name' => 'lakewatch', 'posts_per_page' => 1 ) ); ?>

    Both of them worked in as far as the page continued to show a single blog entry but in both cases I'm still getting a 404 when I click "older posts" at the bottom of the page.

    You can see the page in question here if it helps.

    If someone could point out where I'm going wrong, I'd really appreciate it. Thanks in advance

  2. keesiemeijer
    moderator
    Posted 1 year ago #

    Try it without the query_posts in the template and with this in your theme's functions.php:

    function lakewatch_query( $query ) {
    	// not an admin page and is the main query
    	if ( !is_admin() && $query->is_main_query() ) {
    		// query for category 'lakewatch'
    		if ( is_category( 'lakewatch' ) ) {
    
    			$query->set( 'posts_per_page', 1 );
    
    		}
    	}
    }
    add_action( 'pre_get_posts', 'lakewatch_query' );

    http://codex.wordpress.org/Pagination#Removing_query_posts_from_the_main_loop

  3. CissyH
    Member
    Posted 1 year ago #

    That worked beautifully. Thank you very much!

Topic Closed

This topic has been closed to new replies.

About this Topic