想要插入徽标作为 Wordpress 主题中的中间菜单项


Want to insert a logo as the middle menu item in Wordpress theme

编辑:我调整了参数以将徽标直接插入菜单,而不是填充特定的菜单项。填充方法可以轻松地使居中菜单偏离中心。此插入方法应可解决此问题。

我正在处理一个主题,并想创建一个按徽标分割的菜单。我意识到我可以只创建两个菜单,但我希望它对用户尽可能简化。我已经能够获取项目的数量并定位我想要的菜单项,但我不确定如何使用我的函数.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;  

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

我能够找出问题所在,我想发布我的解决方案,以防其他人正在寻找相同的答案。

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;
}

如果我错过了什么,请随时告诉我,或者是否可以以不同的方式完成。

谢谢!

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

我建议您更改函数名称或在 if else 语句中使用function_exists。

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

快速建议:`

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

'

我正在使用主题页面生成器框架,然后当您自定义外观时,您可以选择一个居中菜单,其中徽标位于中间,菜单被拆分。