Last active
June 16, 2021 16:08
-
-
Save WPVNdev/b9d2dfd4adfad9304e78e46f90ffd196 to your computer and use it in GitHub Desktop.
Loại bỏ số lượng "n" bài viết ra khỏi kết quả hiển thị bài viết mới nhất thông qua thuộc tính "offset" của WordPress Query.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Dùng 1 trong 2 cách bên dưới */ | |
// Cách 1: | |
// 1 query nhưng sẽ gặp lỗi phân trang ở page cuối cùng | |
function numberOfPostsToRemove($query) | |
{ | |
$numOfPosts = 4; | |
if ($query->is_front_page() && $query->is_main_query()) { | |
$paged = get_query_var('paged', 1); | |
$paged = $paged > 0 ? $paged : 1; | |
$offset = $numOfPosts * $paged; | |
$query->set('offset', $offset); | |
} | |
} | |
add_action('pre_get_posts', 'numberOfPostsToRemove'); | |
// Cách 2 | |
// 2 query nhưng không bị lỗi phân trang | |
$numOfPosts = 2; | |
$skipQuery = new WP_Query([ | |
'posts_per_page' => $numOfPosts, | |
'post_type' => 'post', | |
'post_status' => 'publish', | |
'order' => 'DESC', | |
'orderby' => 'ID', | |
]); | |
$skipIds = []; | |
if ($skipQuery->have_posts()) { | |
while ($skipQuery->have_posts()) { | |
$skipQuery->the_post(); | |
$skipIds[] = get_the_ID(); | |
} | |
} | |
function numberOfPostsToRemove($query) | |
{ | |
global $skipIds; | |
if ($query->is_front_page() && $query->is_main_query()) { | |
$query->set('order', 'DESC'); | |
$query->set('orderby', 'ID'); | |
$query->set('post__not_in', $skipIds); | |
} | |
} | |
add_action('pre_get_posts', 'numberOfPostsToRemove'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment