Pagination difficulty using custom query in genesis-based custom theme

I am creating a genesis child theme. I have a category called ‘faculty’ with about 60 posts in it. I am modifying the category template file so that it displays this category in a customized fashion.

The desired result is that

Read More

the faculty appear in random order,
they do not appear more than once
they appear in groups of four per page
Here is the relevant code from my page (category-faculty.php):

remove_action('genesis_loop', 'genesis_do_loop');
add_action('genesis_loop', 'hdo_faculty_loop');

function hdo_faculty_loop() {
  global $paged;
  $args = array(
    'category_name' => 'faculty',
    'posts_per_page' => 4,
    'orderby' => 'rand',
    'paged' => $paged
  );
  genesis_custom_loop(  $args );

}

genesis();

What I am getting is <>:

  • 4 faculty per page [yay!] random order [yay!]
  • previous and next navigation at the bottom of the page [yay!]
  • only 6 pages (24 faculty)instead of the expected 15 [boo!]
  • duplicate faculty in the set of 24 [boo!]
  • a “next” loop on the sixth page that navigates to a 404

Related posts

1 comment

  1. I’m not familiar with Genesis, but most WordPress pagination issues have similar cause. When you load a page in WordPress, the results of the main default query determines the number of available pages. You’re seeing the results of your custom query, but the pagination is based on an entirely different query. This is typically solved by using the pre_get_posts action to modify the main query rather than run a new query:

    function wpa_category( $query ) {
        if ( $query->is_category( 'faculty' ) && $query->is_main_query() ) {
            $query->set( 'posts_per_page', 4 );
            $query->set( 'orderby', 'rand' );
        }
    }
    add_action( 'pre_get_posts', 'wpa_category' );
    

    This won’t entirely solve your issues though- the random order thing will pop up here as well. The problem is that the order isn’t maintained across multiple pages, it’s randomized for each page load. See this answer for a technique to maintain randomized order across multiple pages.

Comments are closed.