Site logo

Archived topic

Different number of posts on 'paged' archives

4 replies · Started by Pete on December 13, 2021

Viewing posts 1–5 of 5

Is there a way I can display more posts on my archives but only after the first archive page of posts?
e.g.
https://www.abc.org.au/category/clubs/ show 6 posts
https://www.nrhsn.org.au/category/clubs/page/2 shows 9 posts

thanks

Hi Pete,

This is a bit tricky to do but it should be possible with filters.

Check this reference - https://codex.wordpress.org/Making_Custom_Queries_using_Offset_and_Pagination

Explanation of usage - https://wordpress.stackexchange.com/questions/155758/have-different-number-of-posts-on-first-page/155782#155782

Example: setting first page to display 3 posts less on category slug clubs.

add_action( 'pre_get_posts', 'sk_query_offset', 1 );
function sk_query_offset( &$query ) {

	// Before anything else, make sure this is the right query...
	if ( ! ( $query->is_category('clubs') || is_main_query() ) ) {
		return;
	}

	// First, define your desired offset...
	$offset = -3;

	// Next, determine how many posts per page you want (we'll use WordPress's settings)
	$ppp = get_option( 'posts_per_page' );

	// Next, detect and handle pagination...
	if ( $query->is_paged ) {

		// Manually determine page query offset (offset + current page (minus one) x posts per page)
		$page_offset = $offset + ( ( $query->query_vars['paged']-1 ) * $ppp );

		// Apply adjust page offset
		$query->set( 'offset', $page_offset );

	}
	else {

		// This is the first page. Set a different number for posts per page
		$query->set( 'posts_per_page', $offset + $ppp );

	}
}

add_filter( 'found_posts', 'sk_adjust_offset_pagination', 1, 2 );
function sk_adjust_offset_pagination( $found_posts, $query ) {

	// Define our offset again...
	$offset = -3;

	// Ensure we're modifying the right query object...
	if ( $query->is_category('clubs') && is_main_query() ) {
		// Reduce WordPress's found_posts count by the offset...
		return $found_posts - $offset;
	}
	return $found_posts;
}

Great find, I was searching for this but couldn't find a thing.

Hmmm it appears this code interferes with GP hooks. All my after archive title/description hooks have disappeared??

Hi there.

can you raise a new topic and share with us what you have hooked in after the archive title ? As i can't see why the above code would affect it.

This archived topic is closed to new replies.