2016-04-14 93 views
0

编辑:我调整了我的参数,直接插入到菜单中的徽标,而不是填充特定的菜单项。填充方法可以轻松地驱动偏离中心的菜单。这种插入方法应该解决这个问题。想要插入一个徽标作为Wordpress主题中的中间菜单项

我正在研究一个主题,并且想创建一个由徽标分开的菜单。我意识到我可以创建两个菜单,但我希望这可以为用户尽可能简化。我已经能够获得项目数量并定位我想要的菜单项,但是我不确定如何使用我的functions.php文件将类“pad-item”添加到<li>

这是我必须找到并指定指定的项目。但是,它所返回的是顶级项目的索引号。

$locations = get_nav_menu_locations(); 
$menu = wp_get_nav_menu_object($locations['primary']); 
$items = wp_get_nav_menu_items($menu->term_id); 
$top_level = 0; 
foreach ($items as $val) { 
    if ($val->menu_item_parent === '0') { 
     $top_level++; 
    } 
} 
$index = round($top_level/2) - 1; 
return $index; 

任何帮助将不胜感激。谢谢。

回答

1

我能弄清楚这个问题,我想发布我的解决方案,以防其他人在寻找相同的答案。

function main($items, $args) { 

    // Checks to see if the menu passed in is the primary one, and creates the logo item for it 
    if ($args->theme_location == 'primary') { 
     $logo_item = '<li class="menu-item">' . get_logo() . '</li>'; 
    } 

    //Gets the location of the menu element I want to insert the logo before 
    $index = round(count_top_lvl_items()/2) + 1; 
    //Gets the menu item I want to insert the logo before 
    $menu_item = get_menu_item($index); 
    $insert_before = '<li id="menu-item-' . $menu_item->ID; 

    $menu_update = substr_replace($items, $logo_item, strpos($items, $insert_before), 0); 

    return $new_menu; 
} 

//Counts the number of top level items in the menu 
function count_top_lvl_items() { 
    $items = get_menu_items(); 
    $counter = 0; 
    foreach ($items as $val) { 
     if ($val->menu_item_parent === '0') { 
      $counter++; 
     { 
    return $counter; 
} 

//Returns the menu item to insert the logo before 
function get_menu_item($index) { 
    $items = get_menu_items(); 
    $counter = 0; 
    foreach ($items as $val) { 
     if ($val->menu_item_parent === '0') { 
      $counter++; 
     } 
     if ($counter == $index) { 
      return $val; 
     } 
    } 
} 

//Returns the logo menu item. I have it separated because my theme allows for varied logos 
function get_logo() { 
    $home = get_option('home'); 
    $logo = get_option('logo'); 
    $logo_item = <<<EOD 

     <div id="logo"> 
      <a href="$home"> 
       <img src="$logo" id="logo-img" alt=""/> 
      </a> 
     </div> 
EOD; 

    return $logo_item; 
} 

function get_menu_items() { 
    $locations = get_nav_menu_locations(); 
    $menu = wp_get_nav_menu_object($locations['primary']); 
    $items = wp_get_nav_menu_items($menu); 
    return $items; 
} 

请随时告诉我,如果我错过了某些东西,或者如果这可以用不同的方式完成。

谢谢!

0

您的函数名可能被其他插件或主题使用,并可能导致问题。

我建议你改变函数名称或在if语句中使用function_exists。

这里是手动>http://php.net/manual/bg/function.function-exists.php

快速建议: '

if(!function_exists('main'){ 
    function main(){ 
     $do_stuff = 'Currently doing'; 
     return $do_stuff; 
    } 
} 

`

相关问题