Community Forums › Forums › Archived Forums › Design Tips and Tricks › something weird is going on when setting posts_per_page
- This topic has 2 replies, 2 voices, and was last updated 10 years ago by
mmjaeger.
-
AuthorPosts
-
July 5, 2015 at 9:22 am #158402
mmjaeger
MemberHello
Hopefully somebody can help:I got a category with 10 posts assign to it - I got the following code in functions.php:
add_action( 'pre_get_posts', 'test' ); function test( $query ) { $num = is_paged() ? 8 : 6; $query->set( 'posts_per_page', $num ); }
I'd like to show a different number of post on the first page - if I put 6 for the first page and 6 for the following page(s) I correctly get 6 post on the first page and 4 on the 2nd page - if I put 8 for the following pages - it only shows me 2 posts on the 2nd page the first page is correct.
any number higher than 8 leads to a 404 when clicking on the pagination.
what am I missing here.
Thank you in advance for your input.
July 5, 2015 at 5:27 pm #158445Victor Font
ModeratorFirst set the number of posts per page to the number you want on the first page. Next, take a look at the following code:
function tax_and_offset_homepage( $query ) { if ($query->is_home() && $query->is_main_query() && !is_admin()) { $query->set( 'post_type', 'my_post_type' ); $query->set( 'post_status', 'publish' ); $query->set( 'ignore_sticky_posts', '-1' ); $tax_query = array( array( 'taxonomy' => 'my_taxo', 'field' => 'slug', 'terms' => array('slug1', 'slug2', 'slug3') ) ); $query->set( 'tax_query', $tax_query ); $ppp = get_option('posts_per_page'); $offset = 1; if (!$query->is_paged()) { $query->set('posts_per_page',$offset + $ppp); } else { $offset = $offset + ( ($query->query_vars['paged']-1) * $ppp ); $query->set('posts_per_page',$ppp); $query->set('offset',$offset); } } } add_action('pre_get_posts','tax_and_offset_homepage'); function homepage_offset_pagination( $found_posts, $query ) { $offset = 1; if( $query->is_home() && $query->is_main_query() ) { $found_posts = $found_posts - $offset; } return $found_posts; } add_filter( 'found_posts', 'homepage_offset_pagination', 10, 2 );
This code let's you have a different number of posts on subsequent pages. Adjust the offset to reflect the the difference in the number of posts between the first page and subsequent pages.
Regards,
Victor
https://victorfont.com/
Call us toll free: 844-VIC-FONT (842-3668)
Have you requested your free website audit yet?July 5, 2015 at 5:35 pm #158446mmjaeger
MemberThank you for your input - I came up with the following code meanwhile - it looks like it's working be I have not fully tested it yet:
$current_page = absint( get_query_var( 'paged' ) ); $offset = $current_page > 2 ? ( $current_page - 2 ) * $post_per_page_subsequent + $posts_per_page_first : $posts_per_page_first;
-
AuthorPosts
- The forum ‘Design Tips and Tricks’ is closed to new topics and replies.