Archived topic
custom queries using offset, pagination issue
3 replies · Started by John on August 22, 2022
Hi, my category pages look like this:
query-loop which outputs the first 4 posts.
And a regular query which outputs the rest of the posts with offset 4.
For offset this snippet is used:
add_action('pre_get_posts', 'the_modified_loop', 10);
function the_modified_loop($query){
if( $query->is_main_query() && !is_admin() && $query->is_category() ) {
$query->set( 'offset', 4 );
}
}
Everything works fine, except the pagination: the same content is displayed on the following pages. https://codex.wordpress.org/Making_Custom_Queries_using_Offset_and_Pagination tried to apply this manual, but it didn't work.
Could you please help me?
Thanx.
Hi there,
yeah offset and pagination creates a whole lot issues. And a lot more code.
See Toms reply here:
add_action('pre_get_posts', 'myprefix_query_offset', 1 );
function myprefix_query_offset(&$query) {
//Before anything else, make sure this is the right query...
if ( ! $query->is_category() || !$query->is_main_query() ) {
return;
}
//First, define your desired offset...
$offset = 4;
//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. Just use the offset...
$query->set('offset',$offset);
}
}
add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
function myprefix_adjust_offset_pagination($found_posts, $query) {
//Define our offset again...
$offset = 4;
//Ensure we're modifying the right query object...
if ( $query->is_category() && $query->is_main_query() ) {
//Reduce WordPress's found_posts count by the offset...
return $found_posts - $offset;
}
return $found_posts;
}
this code helped me.
Glad to hear that!!