我试图在主页的第一页上只显示3个帖子,然后在以下页面显示6个帖子。对于所有内部页面,我只想要每页通常6个帖子。我有这个工作,但它正在网站的所有页面,而不仅仅是主页。我尝试过is_front_page,但这没有用。
add_action( 'pre_get_posts', 'sk_query_offset', 3 );
function sk_query_offset( &$query ) {
// Before anything else, make sure this is the right query...
if ( $query->is_home() && 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 = -6;
// Ensure we're modifying the right query object...
if ( $query->is_home() && is_main_query() ) {
// Reduce WordPress's found_posts count by the offset...
return $found_posts - $offset;
}
return $found_posts;
}
这是主页:www.ninesixty.co.nz/alisonhehir 这是一个内部页面:www.ninesixty.co.nz/alisonhehir/studio
答案 0 :(得分:1)
这将在您的主页上显示3个帖子,然后在您网站上为剩余的分页页面设置的每个帖子。我测试了其他组合,它似乎仍然正常工作。 ceil()函数对于分页非常重要,以确保在计算要显示的总页数时有余数时添加额外页面。这仅在您的主页设置为显示最新帖子时才有效。如果您希望它与静态页面一起使用,那么在本文中documented就会涉及更多内容。
add_action( 'pre_get_posts', 'sk_query_offset', 3 );
function sk_query_offset( &$query ) {
$offset = 3;
$ppp = get_option( 'posts_per_page' );
if ( $query->is_home() && $query->is_main_query() && ! $query->is_paged ) {
$query->set( 'posts_per_page', $offset );
return;
}
if ( $query->is_home() && $query->is_main_query() && $query->is_paged ) {
if( $query->query_vars['paged'] == 2 ) {
$page_offset = $offset;
}
else {
$page_offset = $offset + ( ( $query->query_vars['paged'] - 2 ) * $ppp );
}
$query->set( 'offset', $page_offset );
}
}
add_filter( 'found_posts', 'sk_adjust_offset_pagination', 1, 2 );
function sk_adjust_offset_pagination( $found_posts, $query ) {
$ppp = get_option( 'posts_per_page' );
// We set this value in sk_query_offset
$offset_ppp = $query->query_vars['posts_per_page'];
if ( $query->is_home() && $query->is_main_query() && ! $query->is_paged ) {
// This is important, we need to always round up to the highest integer for calculating the max number of pages.
$max_pages = ceil( $found_posts / $ppp );
return ( $offset_ppp * $max_pages );
}
return $found_posts;
}