Adding custom menu item to WordPress menu

2020-07-13 09:10发布

问题:

I have a WordPress menu that has a few menu items I added through the standard (drag and drop) WordPress admin menu feature. Recently I had to add another item to the menu that generates a dynamic href link. I achieved that using the following code in my functions.php file:

//add my profile menu item dynmacially to the members menu (generate user name based on current user logged in)

add_filter('wp_nav_menu_items','add_profilelink_in_menu', 10, 2);

function add_profilelink_in_menu( $items, $args ) {

if( $args->theme_location == 'secondary')  {

 global $current_user;            
       //converts user id to username           
       $user_info = get_userdata($current_user->ID);

$items .='<li id="menu-item-2091" class="menu-item menu-item-2091">
 <a href="https://www.mysite.com/members/' . $user_info->user_login .'">Profile</a>
 </li>';

  }
  return $items;  

}

My problem is that this menu item is added to the end of the menu and the regular WordPress Menu classes such as 'current-menu-item' don't get applied to this item. Is there a way for me to control the position of where this menu item is added to (For example: add this item after the first two items?)

and how can I get WordPress to treat this dynamically generated menu item as a regular menu item and have it add all the classes that it adds the other menu items (created through the WordPress menu feature)?

Thanks for any help.

回答1:

Here's the logic that you can base using jquery

  //suppose your menu is this
  <ul id="secondary_nav">
    <li id="li_unique_id_1"><a href="">menu 1</a></li>
    <li id="li_unique_id_2"><a href="">menu 2</a></li>
    <li id="li_unique_id_4"><a href="">menu 4</a></li>
</ul>

 //the jquery workaround
 //place this in your footer
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
    <?php
     global $current_user;            
     //converts user id to username           
     $user_info = get_userdata($current_user->ID);
    ?>
    $("<li id='menu-item-2091' class='menu-item menu-item-209'><a href='https://www.mysite.com/members/<?php echo $user_info->user_login; ?>'>Profile</a></li>").insertAfter("#secondary_nav #li_unique_id_2");     
});   
</script>

You can also use insertBefore function



回答2:

Did you check Wordpress menu option in the themes->menu for this ? You can easily add menu from there also you can set custom menu from there.Hope it will help you.



标签: php wordpress