Reply To: [Resolved] How To Get Notification Count? (Code)?
hi ailyroot,
no time to sort out what you need, but see here 3 snippets using different wya to add such item to a theme main menu or custom menu, with fixed or free position… Test and take the one you need.
//fixed position
function my_nav_menu_notif_counter($menu) {
if (!is_user_logged_in())
return $menu;
else
$notif = '<li>Notif '. bp_notifications_get_unread_notification_count( bp_loggedin_user_id() ) .'</li>';
$menu = $menu . $notif;
return $menu;
}
add_filter( 'wp_nav_menu_items', 'my_nav_menu_notif_counter' );
//choose position
function my_nav_menu_positioned_notif_counter( $items, $args )
{
if( $args->theme_location == 'primary' ) // only for primary menu
{
$items_array = array();
while ( false !== ( $item_pos = strpos ( $items, '<li', 3) ) )
{
$items_array[] = substr($items, 0, $item_pos);
$items = substr($items, $item_pos);
}
$items_array[] = $items;
array_splice($items_array, 0, 0, '<li>Notif '. bp_notifications_get_unread_notification_count( bp_loggedin_user_id() ) .'</li>'); // 0,0 is first position, 1,0 is second, etc
$items = implode('', $items_array);
}
return $items;
}
add_filter('wp_nav_menu_items','my_nav_menu_positioned_notif_counter', 10, 2);
// depending the theme, $theme_location may vary and this one use a menu ID
function my_notif_link( $items, $args ) {
$theme_location = 'primary';// Theme Location slug
$existing_menu_item_db_id = 6; // menu id
$new_menu_item_db_id = 66; // unique id number
$label = 'Notificationas '. bp_notifications_get_unread_notification_count( bp_loggedin_user_id() );
$url = bp_core_get_user_domain(bp_loggedin_user_id()) .'notifications/';
if ( $theme_location !== $args->theme_location ) {
return $items;
}
$new_links = array();
if ( is_user_logged_in() ) {
// only if user is logged-in, do sub-menu link
$item = array(
'title' => $label,
'menu_item_parent' => $existing_menu_item_db_id,
'ID' => 'fugit', // menu name
'db_id' => $new_menu_item_db_id,
'url' => $url,
'classes' => array( 'menu-item' )
);
$new_links[] = (object) $item; // Add the new menu item to our array
unset( $item ); // in case we add more items below
$index = count( $items ); // integer, the order number.
// Insert the new links at the appropriate place.
array_splice( $items, $index, 0, $new_links ); // 0,0 is first position, 1,0 is second, etc
}
return $items;
}
add_filter( 'wp_nav_menu_objects', 'my_notif_link', 10, 2 );
Happy testing 😉