如何将自定义菜单添加到 Wordpress 中的特定位置

How to Add Custom Menu to certain Position in Wordpress

我想将自定义菜单添加到我的主菜单,为此我使用了下面的代码,

add_filter( 'wp_nav_menu_items', 'search_menu_item', 10, 2 );
function search_menu_item ( $items, $args ) {
if ($args->theme_location == 'secondary-menu') {
$items .= '<li class="border-none">SEARCH<form><input type="text" name="s" placeholder="Search Here" class="search-box"></form>';
}
return $items;
}

菜单显示为最后一个菜单,但我想将我的菜单添加到第 3 个位置。我该怎么做

有人能帮忙吗??

谢谢

您应该改用 wp_nav_menu_objects 过滤器,它允许您修改项目数组而不是字符串。

示例:

add_filter( 'wp_nav_menu_objects', 'restructure_menu_links', 10, 2 );

function restructure_menu_links( $items, $args ) {

    $new_links = array();

    $label = 'Lorem Ipsum';    // add your custom menu item content here

    // Create a nav_menu_item object
    $item = array(
        'title'            => $label,
        'menu_item_parent' => 0,
        'ID'               => 'yourItemID',
        'db_id'            => '',
        'url'              => $link,
        'classes'          => array( 'menu-item' )
    );

    $new_links[] = (object) $item; // Add the new menu item to our array

    // insert item
    $location = 3;   // insert at 3rd place
    array_splice( $items, $location, 0, $new_links );

    return $items;
}

以下是在 WordPress 中添加自定义菜单的步骤

  1. 首先,进入您的管理->外观->菜单。
  2. 如图所示,单击“+”符号创建一个新菜单。
  3. 当您添加新菜单时,您可以在左侧“主导航”中看到添加的菜单。现在您可以从“自定义 links”、“页面”和“类别”添加菜单项。
  4. 添加菜单项时,您可以在右侧看到该项目。您可以在上图中看到“Yahoo”。它是一个外部 link 菜单项。如果您想将任何菜单项作为任何其他菜单项的子页面,只需拖动该菜单 link 并将其放在父项下方。见上图。在上图中,“Uncategorized”是“yahoo”的子项。
  5. 您可以根据需要创建任意数量的菜单。但是您可以显示与您的主题兼容的菜单。您可以根据需要创建任意数量的菜单。
  6. 只需放置一行代码,您就可以在任何地方调用您的菜单。

           <?php $defaults = array( 'theme_location'  => ,
           'menu'            => ,
           'container'       => 'div',
           'container_class' => 'menu-{menu slug}-container',
           'container_id'    => ,
           'menu_class'      => 'menu',
           'menu_id'         => ,
           'echo'            => true,
           'fallback_cb'     => 'wp_page_menu',
           'before'          => ,
           'after'           => ,
           'link_before'     => ,
           'link_after'      => ,
           'items_wrap'      => '
           <ul id="%1$s" class="%2$s">%3$s</ul>',
           'depth'           => 0,
           'walker'          => );
           ?>
           <?php wp_nav_menu( $args ); ?> 
    

您可以根据需要select 论证。不要忘记在“菜单”参数中包含菜单名称。