@AlexanderFarber, there are many way to attach attribute class under wp_nav_menu
link. I agree with @Sumit, adding page links in Appearance > Menu
WordPress take care of current-menu-item
class or current_page_item
class. Also, this way is best practice to handle your nav menu in the future.
Create dynamic link in wp_nav_menu
Since your question related to this answer, then you have a Page with player
as slug. My approach, after I add those page as menu in Appearance > Menu
( then change label with ‘Profile’ ), I will use filter nav_menu_link_attributes
to make this page have dynamic link. As your question, you use current user id to make it dynamics. Take a look this sample code, say 7
is post/page ID as target:
add_filter( 'nav_menu_link_attributes', function( $atts, $item, $args, $depth )
{
// check our nav_menu
if ( is_object( $args ) && is_object( $item ) && 'primary-menu' == $args->menu_id )
{
$post_id = 7; // Define Post or Page ID
$user = wp_get_current_user();
if ( 0 < $user->ID && $post_id == $item->object_id )
$atts['href'] = esc_url( user_trailingslashit( untrailingslashit( $item->url ) . '-' . $user->ID ) );
}
return $atts;
} 10, 4 );
You need to check which menu before you make change, since your filter will effect another menu in the same page. By this approach you don’t get trouble in attribute ( class or id theme css related ) of the current page.
Answer related your code
Yes I know you need to add custom link by filter wp_nav_menu_items
and add class attribute for the current page, almost the same with your answer. Since it related to Page, I use current_page_item
as class attribute that match with css TwentyThirteen to make highlight of item nav menu.
add_filter( 'wp_nav_menu_items', 'my_nav_menu_items', 10, 2 );
function my_nav_menu_items( $items, $args )
{
if ( is_object( $args ) && 'primary-menu' == $args->menu_id )
{
$user = wp_get_current_user();
$with_user_id = ( 0 != $user->ID ) ? '-' . $user->ID : '';
$post_id = 7; // Post or Page ID
$class = ( is_page( $post_id ) ) ? 'current_page_item' : '';
$items .= sprintf( '<li id="menu-item-32" class="menu-item menu-item-type-custom
menu-item-object-custom %1$s menu-item-32"><a href="%2$s">%3$s</a></li>',
sanitize_html_class( $class ),
esc_url( user_trailingslashit( untrailingslashit( get_page_link( $post_id ) ) . $with_user_id ) ),
__( 'Profile', 'textdomain' )
);
}
return $items;
}
You can tweak the code to adjust with your current project. I hope this helps.