WordPress: Add empty list-item to navigation menu

2019-06-02 07:34发布

问题:

<ul id="menu-primary">
    <li></li>
    <li></li>
    <li></li><li class="stretcher"></li> /* add adjacent to the last menu item */
</ul>

I need to add <li class="stretcher"></li> adjacent to the last menu item exactly as shown, to the menu with id="menu-primary".

(The reason is to remove the whitespace generated in some browsers. Similar to the first answer in this question: Fluid width with equally spaced DIVs)

回答1:

I'd add it with a filter:

add_filter('wp_nav_menu_items', 'add_stretcher', 10, 2);
function add_stretcher($items, $args) {
  if ($args->theme_location == 'primary') {
    $items .= '<li class="stretcher"></li>';
  }
  return $items;
}


回答2:

You can add it using jQuery with following code

<script>
   jQuery(document).ready(function(){
      jQuery("#menu-primary li").last().before("<li class="stretcher"></li>");                             
   });
</script>