【问题标题】:WordPress: add HTML to a specific nav menuWordPress:将 HTML 添加到特定的导航菜单
【发布时间】:2013-09-07 06:50:53
【问题描述】:
add_filter('wp_nav_menu_items', 'add_custom', 10, 2);
function add_custom($items, $args) {
  if ($args->theme_location == 'primary') {
    $items .= '<li class="custom"></li>';
  }
  return $items;
}

产生:

<ul id="menu-top">
    <li></li>
    <li></li>
    <li></li>
    <li class="custom"></li> /* added custom HTML */
<ul>

但是如果我的 WP 菜单没有“theme_location”怎么办?我可以通过 id/class 而不是“theme_location”来定位我的菜单,或者我可以如何将 HTML 添加到一个特定的菜单?

【问题讨论】:

  • 假设您使用的是外观 -> 菜单编辑器,您可以添加一个页面,向页面添加一个特定的类并将其隐藏,而 CSS 则不能。我不知道你还需要什么,所以这可能无济于事。
  • 我有一个具体的案例,所以我不能这样做。我简化了我的问题以避免不必要的复杂化,但可以在这里找到更多关于我正在尝试做的事情的细节stackoverflow.com/questions/18658643/…
  • 为什么不添加主题位置?
  • 我想知道是否可以简单地使用菜单的 id/class 代替。我想为它分配一个主题位置,所以如果我添加register_nav_menu( 'primary', 'Primary Menu' ); 并将我的菜单分配给“主菜单”,我还需要做什么?
  • 我相信这就是您所要做的,但在此之前,您是否尝试过检查 $args 数组以查看其中是否包含 id?

标签: php html wordpress menu navigation


【解决方案1】:

你会使用 jQuery 吗?

jQuery(document).ready(function($) {
    $('#menu-top').append('<li class="custom"></li>');
});

或 PHP + CSS - 使用此解决方案,您可以将其添加到每个菜单并在需要时通过 CSS 将其隐藏。

add_filter('wp_nav_menu_items', 'add_custom', 10, 2);
function add_custom($items, $args) { 
   $items .= '';
   return $items;
}
li.custom { display:none; } // hide originally
ul#menu-top li.custom { display:inline; } // or whatever styles

【讨论】:

  • @Sunny 我显然不知道实际的答案,但我提供了另一种您可以使用的解决方案。
【解决方案2】:

当没有 theme_location 时,我猜它会退回到 wp_page_menu。因此,理论上,您可以过滤到wp_page_menu 并修改输出。

<?php
//Use this filter to modify the complete output
//You can get an argument to optionally check for the right menu
add_filter( 'wp_page_menu', 'my_page_menu', 10, 2 );
/**
 * Modify page menu
 * @param  string $menu HTML output of the menu
 * @param  array $args Associative array of wp_page_menu arguments
 *                     @see http://codex.wordpress.org/Function_Reference/wp_page_menu
 * @return string       menu HTML
 */
function my_page_menu( $menu, $args ) {
    //see the arguments
    //Do something with $menu
    return $menu;
}

//Use this filter to alter the menu argument altogether
//It is fired before creating any menu html
add_filter( 'wp_page_menu_args', 'my_page_menu_pre_arg', 10, 1 );
/**
 * Modify page menu arguments
 * @param  array $args Associative array of wp_page_menu arguments
 *                     @see http://codex.wordpress.org/Function_Reference/wp_page_menu
 * @return array       modified arguments
 */
function my_page_menu_pre_arg( $args ) {
    //Do something with $args
    return $args;
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2019-11-09
    • 2021-06-29
    相关资源
    最近更新 更多