admin管理员组文章数量:1134247
In this moment I have a code to show the count on categories, the problem is that the parent categories display always 0, insted of the sum of posts in children categories
function custom_add_count_on_archive_title( $title ) {
$term = get_queried_object();
if( $term instanceof WP_Term && 'category' === $term->taxonomy ) {
$title .= ' <span>'.$term->count.'</span>';
}
return $title;
}
add_filter( 'get_the_archive_title', 'custom_add_count_on_archive_title', 10, 1 );
What I should add to this code?
In this moment I have a code to show the count on categories, the problem is that the parent categories display always 0, insted of the sum of posts in children categories
function custom_add_count_on_archive_title( $title ) {
$term = get_queried_object();
if( $term instanceof WP_Term && 'category' === $term->taxonomy ) {
$title .= ' <span>'.$term->count.'</span>';
}
return $title;
}
add_filter( 'get_the_archive_title', 'custom_add_count_on_archive_title', 10, 1 );
What I should add to this code?
Share Improve this question edited Aug 10, 2023 at 7:14 YourManDan 4342 silver badges12 bronze badges asked Aug 4, 2023 at 8:04 Andrea SacconiAndrea Sacconi 797 bronze badges2 Answers
Reset to default 0You could add this to your code:
function custom_add_count_on_archive_title( $title ) {
$term = get_queried_object();
$term_id = get_queried_object()->term_id;
if( $term instanceof WP_Term && 'category' === $term->taxonomy ) {
$children_terms = get_terms(array(
'taxonomy' => 'category',
'child_of' => $term_id,
));
$total_count = 0;
if (!empty($children_terms) && !is_wp_error($children_terms)) {
foreach ($children_terms as $child_term) {
$total_count += $child_term->count;
}
}
$title .= ' <span>'.$total_count.'</span>';
}
return $title;
}
add_filter( 'get_the_archive_title', 'custom_add_count_on_archive_title', 10, 1 );
Have not tested it but theoretically it should work. What it does is gets the children of the current term. Iterates through them and totals the count of them.
This is the right code:
function custom_add_count_on_archive_title( $title ) {
$term = get_queried_object();
$term_id = $term->term_id;
if( $term instanceof WP_Term && 'category' === $term->taxonomy ) {
$children_terms = get_terms(array(
'taxonomy' => 'category',
'child_of' => $term_id,
));
$total_count = $term->count;
if (!empty($children_terms) && !is_wp_error($children_terms)) {
foreach ($children_terms as $child_term) {
$total_count += $child_term->count;
}
}
$title .= ' <span>'.$total_count.'</span>';
}
return $title;
}
add_filter( 'get_the_archive_title', 'custom_add_count_on_archive_title', 10, 1 );
本文标签: Adding count also to parent categories
版权声明:本文标题:Adding count also to parent categories 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736807124a1953736.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论