WP add logo into center of menu whist ignoring sub

2019-09-13 09:46发布

Using the following jQuery form another post I'm able to dynamically center a logo in the middle of a wordpress menu but when I add a sub menu to the main nav, the logo dissapears. How would I re-write this to discount any sub menus?

JQuery:

var position = $("ul#main_nav li").length-2;
                        var i = 0;
                        $('ul#main_nav li').each(function() {
                            if(i == position/2) {
                            $(this).after('<img src="<?php echo get_template_directory_uri(); ?>/img/logo.png" alt="Logo" class="logo-img">');
                            }
                            i++;
                        });

HTML:

<ul id="#main_nav">
    <li>ITEM1</li>
    <li>ITEM2
        <ul class="sub-menu">
            <li>SUB-ITEM1</li>
            <li>SUB-ITEM2</li>
            <li>SUB-ITEM3</li>
        </ul>
    </li>
    <li>ITEM3</li>
    <li>ITEM4</li>
    <li>ITEM5</li>
    <li>ITEM6</li>
</ul>

2条回答
我命由我不由天
2楼-- · 2019-09-13 10:26

If by any chance anyone else comes across this issue, here's the fix..

var position = $("ul#main_nav li.menu-item-object-page").length-2;
var i = 0;
    $('ul#main_nav li.menu-item-object-page).each(function() {
        if(i == position/2) {
        $(this).after('<img src="<?php echo get_template_directory_uri(); ?>/img/logo.png" alt="Logo" class="logo-img">');
    }
 i++;
});

Wordpress gives top level nav list items the class .menu-item-object-page but doesn't apply this to sub menu items so by being a bit more specific about what elemnets to target I've got the result I wanted.

查看更多
Deceive 欺骗
3楼-- · 2019-09-13 10:28
var position = $("ul#main_nav > li").length-2;
                    var i = 0;
                    $('ul#main_nav li').each(function() {
                        if(i == position/2) {
                        $(this).after('<img src="<?php echo get_template_directory_uri(); ?>/img/logo.png" alt="Logo" class="logo-img">');
                        }
                        i++;
                    });
    /* Try this */
查看更多
登录 后发表回答