Hi Guido!
Based on the documentation, you can’t use offset because setting the parameter can break the pagination.
// https://developer.ww.wp.xz.cn/reference/classes/wp_query/ > Pagination Parameters
offset (int) – number of post to displace or pass over. Warning: Setting the offset parameter overrides/ignores the paged parameter and breaks pagination. The ‘offset’ parameter is ignored when ‘posts_per_page’=>-1 (show all posts) is used.
There is a workaround before, but it’s no longer available in the documentation. You can try this snippet in the functions.php file instead.
add_action('pre_get_posts', 'nfg_query_offset', 1 );
function nfg_query_offset(&$query) {
if ( ! $query->is_home() ) {
return;
}
// define the offset here
$offset = 1;
$ppp = get_option('posts_per_page');
if ( $query->is_paged ) {
$page_offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );
$query->set('offset', $page_offset );
}
else {
$query->set('offset',$offset);
}
}
function nfg_adjust_offset_pagination($found_posts, $query) {
// define the offset here
$offset = 1;
if ( $query->is_home() ) {
return $found_posts - $offset;
}
return $found_posts;
}
add_filter('found_posts', 'nfg_adjust_offset_pagination', 1, 2 );
Best Regards,
Ismael
Thread Starter
Guido
(@guido07111975)
Hi Ismael,
I did read the documentation and could not believe it breaks the pagination, except when using parameter with value posts_per_page="-1", but apparently it does break it when using the offset.
I will try the snippet, but in my case the offset is part of a shortcode (it’s a shortcode attribute, not a static value), so that makes it more complex, because this snippet should be used before building/rendering the shortcode.
Guido
Hiya Guido!
Once you recognize that “posts_per_page” gets translated into a MySQL LIMIT clause just as “offset” does, perhaps you can see why the two are mutually exclusive. One solution to custom query pagination is taking it away from “posts_per_page” and calculating the appropriate offset for yourself. If there’s an additional offset from a shortcode argument, I suspect you’ll also then need to calculate your own pagination offset and factor the two together.
Thread Starter
Guido
(@guido07111975)
Hi BC,
Meanwhile I took another look at the code of wp_query and did notice pagination is ignored when offset is being used. I don’t want to hook into the query too much, to avoid unexpected behaviour (and also I don’t have enough knowledge to do this). So I guess I will leave it alone and simply disable the pagination links underneath my posts when offset is being used 😉
Guido