如何在WordPress的主导航菜单中添加自定义分类后计数
我使用以下代码在主导航菜单中添加了类别帖子计数:如何在WordPress的主导航菜单中添加自定义分类后计数,wordpress,Wordpress,我使用以下代码在主导航菜单中添加了类别帖子计数: add_filter('the_title', 'wpse165333_the_title', 10, 2); function wpse165333_the_title($title, $post_ID) { if( 'nav_menu_item' == get_post_type($post_ID) ) { if( 'taxonomy' == get_post_meta
add_filter('the_title', 'wpse165333_the_title', 10, 2);
function wpse165333_the_title($title, $post_ID)
{
if( 'nav_menu_item' == get_post_type($post_ID) )
{
if( 'taxonomy' == get_post_meta($post_ID, '_menu_item_type', true) && 'category' == get_post_meta($post_ID, '_menu_item_object', true) )
{
$category = get_category( get_post_meta($post_ID, '_menu_item_object_id', true) );
$title .= sprintf(' (%d)', $category->count);
}
}
return $title;
}
$taxonomy= get_taxonomy( get_post_meta($post_ID, '_menu_item_object_id', true) );
$title .= sprintf(' (%d)', $taxonomy->count);
我还想在主导航中的自定义分类菜单项中添加post计数。
我添加了以下代码:
add_filter('the_title', 'wpse165333_the_title', 10, 2);
function wpse165333_the_title($title, $post_ID)
{
if( 'nav_menu_item' == get_post_type($post_ID) )
{
if( 'taxonomy' == get_post_meta($post_ID, '_menu_item_type', true) && 'category' == get_post_meta($post_ID, '_menu_item_object', true) )
{
$category = get_category( get_post_meta($post_ID, '_menu_item_object_id', true) );
$title .= sprintf(' (%d)', $category->count);
}
}
return $title;
}
$taxonomy= get_taxonomy( get_post_meta($post_ID, '_menu_item_object_id', true) );
$title .= sprintf(' (%d)', $taxonomy->count);
然而,什么也没有发生。
如何将帖子编号添加到主菜单中的自定义分类菜单项
谢谢。您可以通过以下内容获得分类计数:
get_term_by( $field, $value, $taxonomy );
其中:
$field=id、名称或slug
$value=要查找的分类的id、名称或slug
$taxonomy=分类类型的名称
(见附件)
例如
$my_taxonomy = get_term_by( 'name', 'Horror', 'books' );
$count = $my_taxonomy->count;
谢谢你的评论。我想wp_count_terms会返回术语的数量而不是post count…更改了我的答案,请尝试:)非常感谢。我将尝试使用get_term_by。