In a Twenty Thirteen child theme I append a menu item (a link to /player-number page template, where the number is different for each user and represents her or his id in a game database) using the wp_nav_menu_items hook:
function my_nav_menu_items( $items ) {
$profile = sprintf('<li id="menu-item-32"
class="menu-item menu-item-type-custom
menu-item-object-custom menu-item-32">
<a href="/player-%d/#navbar">Profile</a></li>',
42); // 42 is just a placeholder here, representing user id
return $items . $profile;
}
add_filter( 'wp_nav_menu_items', 'my_nav_menu_items' );
And that item is visible and clickable in the primary-menu
, but for some reason it is never highlighted (apologies for non-english text in the screenshot):
I.e. when I click at any other menu entry - it changes its color to reddish one and the font slant to italics:
But the last menu item does not do that, why?
UPDATE:
The wp_nav_menu_objects filter seems to be more suitable for the task of adding a menu item and I have tried using it in my /wp-content/themes/twentythirteen-child/functions.php file:
function my_nav_menu_objects( $sorted_menu_items )
{
$link = array (
'title' => 'Profile',
'menu_item_parent' => 0,
'ID' => 32,
'url' => '/player-42',
);
$sorted_menu_items[] = (object) $link;
error_log(print_r($sorted_menu_items, TRUE));
return $sorted_menu_items;
}
add_filter( 'wp_nav_menu_objects', 'my_nav_menu_objects' );
but it suffers the same problem: the menu item is added, but it is not highlighted (the CSS style current-menu-item
for that is missing) when selected.
UPDATE 2:
Also I have tried adding a menu item called "Profile" manually and then searching and replacing its url
with the following code:
function my_nav_menu_objects( $sorted_menu_items )
{
foreach ( $sorted_menu_items as $item ) {
error_log(print_r($item, TRUE));
if ( $item->title == 'Profile' ) {
$item->url = '/player-42';
break;
}
}
return $sorted_menu_items;
}
add_filter( 'wp_nav_menu_objects', 'my_nav_menu_objects' );
with the same effect (the URL has changed, but CSS highlighting is missing, when that URL is selected).
/player-ID
is dynamic and based on the current user id, but I think it is not really relevant for my question: How to add a menu item using the wp_nav_menu_items filter - so that it works properly (i.e. the focus works)?