我试图显示 WordPress 中主要类别的帖子总数,而不是显示所有帖子。
如何限制不分页显示的帖子总数?
以下方法不起作用:
function target_main_category_query_with_conditional_tags( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
if ( is_category(array( 45, 49 )) ) {
$query->set( 'posts_per_page', 9 );
$query->set( 'nopaging', true );
}
}
}
add_action( 'pre_get_posts', 'target_main_category_query_with_conditional_tags' );
此代码操作类别页面。
<?php
function target_main_category_query_atakanau( $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_category() && $query->get_queried_object()->parent == 0 ) {
$query->set( 'posts_per_page', 2 );
$query->set( 'no_found_rows', true );
// Adds HTML to the category description:
add_filter( 'category_description', 'add_content_to_category_description_atakanau', 10, 2);
}
}
function add_content_to_category_description_atakanau( $description , $category_id) {
$total_post_count = total_posts_of_category_atakanau($category_id);
$new_description = $description . '<p>This category contains a total of '.$total_post_count.' posts.</p>';
return $new_description;
}
function total_posts_of_category_atakanau($category_id) {
$total_post_count = 0;
$subcategories = get_categories( array(
'child_of' => $category_id,
) );
foreach ( $subcategories as $subcategory ) {
$total_post_count += $subcategory->count;
}
// Add the post count of the given category itself
$main_category = get_category( $category_id );
$total_post_count += $main_category->count;
return $total_post_count;
}
add_action( 'pre_get_posts', 'target_main_category_query_atakanau' );
条件:
! is_admin()
:没有管理员角色的访客
$query->is_category()
:分类页面
$query->get_queried_object()->parent == 0
:父类别
注意:正如@Karl Hill所说,
nopaging
参数会覆盖posts_per_page
,请勿使用它。