My WP menu structure looks like this (simplified)
<ul>
<li class="dashboard menu-item ... menu-item-56"><a href=#link">WP link</a></li>
<li class="messages menu-item ... menu-item-57"><a href=#custom-link">Messages</a></li>
<li class="profile menu-item ... menu-item-58"><a href=#link">WP link 2</a></li>
</ul>
Now it'd like to add a label/badge with a counter in it but only when the css class "messages" is used.
The counter will be a variable
, so this...
<li class="messages menu-item ... menu-item-57"><a href=#link">Messages</a></li>
...should become...
<li class="messages menu-item ... menu-item-57">
<a href=#link">Messages</a><span class="counter">'. $counter .'</span>
</li>
[![enter image description here][1]][1]
My starter's code...
function add_counter_comments($items, $args) {
if ($args->theme_location == 'my_custom_menu' ) {
//what code should I add?
}
return $items;
}
add_filter('wp_nav_menu_items', 'add_counter_comments', 10, 2);
Update:
My counter looks like this, but I don't see why it doesn't get added.
$current_user = wp_get_current_user();
$args = array(
'post_author' => $current_user->ID,
'status' => 'approve',
//...
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
$comment_count = 0;
foreach ($comments as $comment) {
$comment_count++;
}
$counter = $comment_count;
And then change this line
$item_output .= sprintf( ' <span class="counter">%d</span>', $counter );
I even tested it with this but that didn't worked either.
$item_output .= $counter;
meta_query/meta_key
attached to it. I'd like to show my counter only next to the menu link with the classmessages
if there are new unread messages (comments) and not to any other menu links. The code you shared adds the counter to all menu links and I'm having a hard time to tweak this a bit.