我有一个由 WordPress 主题内置的自定义帖子类型。在用户后端,他们可以查看已创建的自定义帖子类型帖子的列表。默认情况下,每页显示的帖子数仅为 20。
我想将每页显示的自定义帖子类型帖子从 20 个更改为 100 个。
这是我在functions.php中使用的PHP代码:
// Change the number of custom post type posts per page - WORKING
$current_user = wp_get_current_user();
if(!$current_user->roles[0] !=='administrator') {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type'=>'my_post_type', // Your post type name
'posts_per_page' => 100,
'paged' => $paged // make sure it is without , for the last element
);
$wp_query = new WP_Query( $args );
}
以上代码运行良好;这意味着用户后端每页显示的自定义帖子类型帖子数量现在为 100。
但是,分页不再起作用:
计算错误 - 页数与默认值相同,计算如下:
-The total number of posts is 12581
-for 20 posts per page, there should be 12581/20 = 630 pages
-For 100 posts per page, there should be 12581/100 = 126 pages
无论每页显示多少个帖子,页数都保持为 630(默认)
Please check a screenshot below for your info.
https://imgur.com/a/oeUVRqu
单击下一页时,它会显示相同的自定义帖子类型帖子。请检查屏幕截图以获取您的信息。
-First page:
https://imgur.com/a/muzlFEV
-Second page:
https://imgur.com/a/ywKlZla
是否有不同的方法可以正确定义每页的帖子数而不影响分页?
非常感谢任何帮助。
出现此问题是因为您直接修改主 $wp_query 对象,这可能会导致分页出现意外行为。
以下是如何修改代码以正确调整每页自定义帖子类型帖子的数量,而不影响分页:
function modify_cpt_posts_per_page( $query ) {
if ( ! is_admin() && $query->is_main_query() && is_post_type_archive( 'my_post_type' ) ) {
if ( ! current_user_can( 'administrator' ) ) {
$query->set( 'posts_per_page', 100 ); // Change this to your desired number
}
}
}
add_action( 'pre_get_posts', 'modify_cpt_posts_per_page' );