Id like to have on homepage on first page posts only from certain category and when user click to next page, he will see everything else.
I added this to my functions.php :
function my_home_category ($query) {
if ( $query->is_home() && !($query->is_paged()) && $query->is_main_query() ) {
$query->set( 'cat', '2');
}
}
add_action ('pre_get_posts', 'my_home_category');
And it works. The only problem is, when I go to page 2
, I see posts that would normally be at page 2 (if I didnt have this function) and not the newest posts from all categories. So if earlier there were some posts from other categories on the first page, I cant see them now anywhere.
So before the function my blog was like:
Page1: A, B, C, B, A <br>
Page2: B, A, A, C, B <br>
(A means post from category A ...)
And I would like to have it like this:
Page1: B, B, B, B, B <br>
Page2: A, C, A, A, A <br>
Page3: C ... <br>
But what happened is:
Page1: B, B, B, B, B <br>
Page2: B, A, A, C, B <br>
Can you help me please ?
Modify your function something to:
function my_home_category ($query) {
if ( $query->is_home() && !($query->is_paged()) && $query->is_main_query() ) {
$query->set( 'cat', '2');
}
else{
//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 );
}
}
add_action ('pre_get_posts', 'my_home_category');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.