Mega Menu Walker


10

我正在尝试创建一个大型菜单浏览器。不幸的是,步行者完全逃避了我的编码知识。我真的可以使用一些帮助使其正常工作。这是我需要的功能:

  • 总结第二级<ul><section>[完成]
  • 当用户<li>在第二级中将类“ break”设置<ul>为时,<li>请重新开始<ul>。如果它是<li>列表中的第一个列表,则不要执行任何操作以防止形成空的无序列表。[完成]
  • 当用户<li>在具有子级的第一级中将类“ widget”设置为时<ul>,请将小部件附加到该类的末尾<ul>[完成]
  • 将类添加mega-menu-columns-#<li>包含具有多个列和/或小部件的下拉菜单的第一级元素中。#表示<ul>元素数,小部件+1(如果存在)。[完成]

我有一些代码可以执行某些操作,但不是全部。以下是切除部分:

将第二级包装<ul><section>

function start_lvl(&$output, $depth = 0, $args = array()) {
    if ($depth == 0) {
        $output .= "<section>";
    }
    $output .= "<ul class=\"sub-menu\">";
}
function end_lvl(&$output, $depth = 0, $args = array()) {
    $output .= "</ul>";
    if ($depth == 0) {
        $output .= "</section>\n";
    }
}

生成小部件HTML:

ob_start();
dynamic_sidebar("Navigation Callout");
$widget = ob_get_contents();
ob_end_clean();

输出的HTML将是:

<ul>
    <li id="menu-item-1" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-1 mega-menu-columns-2">
        <a href="http://www.example.com/about/">
            About Us
        </a>
        <section>
            <ul class="sub-menu">
                <li id="menu-item-2" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-2">
                    <a href="http://www.example.com/about/company-profile/">
                        Company Profile
                    </a>
                </li>
                <li id="menu-item-3" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-3">
                    <a href="http://www.example.com/about/leadership-team/">
                        Leadership Team
                    </a>
                </li>
                <li id="menu-item-4" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4">
                    <a href="http://www.example.com/about/professional-affiliations/">
                        Professional Affiliations
                    </a>
                </li>
            </ul>
            <ul class="sub-menu">
                <li id="menu-item-5" class="break menu-item menu-item-type-post_type menu-item-object-page menu-item-5">
                    <a href="http://www.example.com/about/clients/">
                        Clients
                    </a>
                </li>
                <li id="menu-item-6" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-6">
                    <a href="http://www.example.com/about/partnerships/">
                        Partnerships
                    </a>
                </li>
            </ul>
        </section>
    </li>
    <li id="menu-item-7" class="widget menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-7 mega-menu-columns-3">
        <a href="http://www.example.com/services/">
            Services
        </a>
        <section>
            <ul class="sub-menu">
                <li id="menu-item-8" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-8">
                    <a href="http://www.example.com/services/civil-engineering/">
                        Civil Engineering
                    </a>
                </li>
                <li id="menu-item-9" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-9">
                    <a href="http://www.example.com/services/land-planning/">
                        Land Planning
                    </a>
                </li>
                <li id="menu-item-10" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10">
                    <a href="http://www.example.com/services/surveying/">
                        Surveying
                    </a>
                </li>
            </ul>
            <ul class="sub-menu">
                <li id="menu-item-11" class="break menu-item menu-item-type-post_type menu-item-object-page menu-item-11">
                    <a href="http://www.example.com/services/information-technology/">
                        Information Technology
                    </a>
                </li>
                <li id="menu-item-12" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-12">
                    <a href="http://www.example.com/services/subsurface-utility-engineering/">
                        Subsurface Utility Engineering
                    </a>
                </li>
            </ul>
            <aside>
                <h6>Widget Title</h6>
                <p>Maecenas quis semper arcu. Quisque consequat risus nisi. Sed venenatis urna porta eros malesuada euismod. Nulla sollicitudin fringilla posuere. Nulla et tellus eu nisi sodales convallis non vel tellus.</p>
            </aside>
        </section>
    </li>
    <li id="menu-item-13" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-15">
        <a href="http://www.example.com/contact/">
            Contact Us
        </a>
    </li>
</ul>

更新:我的柜台让我感到悲伤。它们只是在生成子菜单之后才计数,这对我没有帮助。查看此屏幕截图以了解我的意思:

最高的数字正在被提取start_el。底数被拉入end_el。如您所见,最高人数并没有.breaks像我应该的那样算我。他们计算小部件类,因为它们被计入$depth = 0。有人请把我从这种恐怖中救出来!

// mega menu walker
/*
    ONE REMAINING BUG:
    - Need to add class to LI containing mega-menu-columns-#
*/
class megaMenuWalker extends Walker_Nav_Menu {
    private $column_limit = 3; /* needs to be set for each site */
    private $show_widget = false;
    private $column_count = 0;
    static $li_count = 0;
    function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        $classes = empty($item->classes) ? array() : (array) $item->classes;
        $item_id = $item->ID;
        if ($depth == 0) self::$li_count = 0;
        if ($depth == 0 && in_array("widget", $classes)) {
            $this->show_widget = true;
            $this->column_count++;
        }
        if ($depth == 1 && self::$li_count == 1) {
            $this->column_count++;
        }
        if ($depth == 1 && in_array("break", $classes) && self::$li_count != 1 && $this->column_count < $this->column_limit) {
            $output .= "</ul><ul class=\"sub-menu\">";
            $this->column_count++;
        }
        if ($depth == 0 && $this->column_count > 0) {
            $mega_menu_class = " mega-menu-columns-" . $this->column_count;
        }
        $class_names = join(" ", apply_filters("nav_menu_css_class", array_filter($classes), $item));
        $class_names = " class=\"" . esc_attr($class_names . $mega_menu_class) . "\"";
        $output .= sprintf(
            "<li id=\"menu-item-%s\"%s><a href=\"%s\">%s</a>",
            $item_id,
            $class_names,
            $item->url,
            $item->title
        );
        self::$li_count++;
    }
    function start_lvl(&$output, $depth = 0, $args = array()) {
        if ($depth == 0) {
            $output .= "<section>";
        }
        $output .= "<ul class=\"sub-menu\">";
    }
    function end_lvl(&$output, $depth = 0, $args = array()) {
        $output .= "</ul>";
        if ($depth == 0) {
            if ($this->show_widget) {
                ob_start();
                dynamic_sidebar("Navigation Callout");
                $widget = ob_get_contents();
                ob_end_clean();
                $output .= $widget;
                $this->show_widget = false;
            }
            $output .= "</section>";
        }
    }
    function end_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        if ($depth == 0 && $this->column_count > 0) {
            /* needs to be added to opening level 0 li */
            $column_count_class = " mega-menu-columns-" . $this->column_count;
            $output .= $column_count_class;
            /* end */
            $this->column_count = 0;
        }
        $output .= "</li>";
    }
}   

更新2:这是带有注释的输出示例,该注释描述了mega-menu-columns-类应如何计数:

<ul>
    <!-- +1 because this has a class of "widget" -->
    <li id="menu-item-1" class="widget menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-1 mega-menu-columns-3">
        <a href="http://www.example.com/about/">
            About Us
        </a>
        <!-- +1 because a drop down exists -->
        <!-- gets added by my walker -->
        <section>
        <!-- end gets added by my walker -->
            <ul class="sub-menu">
                <!-- +0 because this "break" is the first child -->
                <li id="menu-item-2" class="break menu-item menu-item-type-post_type menu-item-object-page menu-item-2">
                    <a href="http://www.example.com/about/company-profile/">
                        Company Profile
                    </a>
                    <ul>
                        <!-- +0 because this "break" is in level 2 -->
                        <li id="menu-item-3" class="break menu-item menu-item-type-post_type menu-item-object-page menu-item-3">
                            <a href="http://www.example.com/about/our-team/">
                                Our Team
                            </a>
                        </li>
                    </ul>
                </li>
                <li id="menu-item-4" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4">
                    <a href="http://www.example.com/about/leadership-team/">
                        Leadership Team
                    </a>
                </li>
                <li id="menu-item-5" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-5">
                    <a href="http://www.example.com/about/professional-affiliations/">
                        Professional Affiliations
                    </a>
                </li>
            <!-- gets added by my walker -->
            </ul>
            <ul class="sub-menu">
            <!-- end gets added by my walker -->
                <!-- +1 because this "break" is in level 1 and not the first child -->
                <li id="menu-item-6" class="break menu-item menu-item-type-post_type menu-item-object-page menu-item-6">
                    <a href="http://www.example.com/about/clients/">
                        Clients
                    </a>
                </li>
                <li id="menu-item-7" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-7">
                    <a href="http://www.example.com/about/partnerships/">
                        Partnerships
                    </a>
                </li>
            </ul>
            <!-- gets added by my walker for .widget -->
            <section>
                <header>
                    <h1>Widget Title</h1>
                </header>
                <p>This is a widget. It was hard to make appear!</p>
            </section>
            <!-- end gets added by my walker for .widget -->
        <!-- gets added by my walker -->
        </section>
        <!-- end gets added by my walker -->
    </li>
</ul>

更新:这是我最后的Walker and Functions。这正是我想要的。谢谢您的帮助!

// mega menu walker
class megaMenuWalker extends Walker_Nav_Menu {
    private $column_limit = 3;
    private $show_widget = false;
    private $column_count = 0;
    static $li_count = 0;
    function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        $classes = empty($item->classes) ? array() : (array) $item->classes;
        $item_id = $item->ID;
        if ($depth == 0) {
            self::$li_count = 0;
        }
        if ($depth == 0 && in_array("widget", $classes)) {
            $this->show_widget = true;
            $this->column_count++;
        }
        if ($depth == 1 && self::$li_count == 1) {
            $this->column_count++;
        }
        if ($depth == 1 && in_array("break", $classes) && self::$li_count != 1 && $this->column_count < $this->column_limit) {
            $output .= "</ul><ul class=\"sub-menu\">";
            $this->column_count++;
        }
        $class_names = join(" ", apply_filters("nav_menu_css_class", array_filter($classes), $item)); // set up the classes array to be added as classes to each li
        $class_names = " class=\"" . esc_attr($class_names) . "\"";
        $output .= sprintf(
            "<li id=\"menu-item-%s\"%s><a href=\"%s\">%s</a>",
            $item_id,
            $class_names,
            $item->url,
            $item->title
        );
        self::$li_count++;
    }
    function start_lvl(&$output, $depth = 0, $args = array()) {
        if ($depth == 0) {
            $output .= "<section>";
        }
        $output .= "<ul class=\"sub-menu\">";
    }
    function end_lvl(&$output, $depth = 0, $args = array()) {
        $output .= "</ul>";
        if ($depth == 0) {
            if ($this->show_widget) {
                ob_start();
                dynamic_sidebar("Navigation Callout");
                $widget = ob_get_contents();
                ob_end_clean();
                $output .= $widget;
                $this->show_widget = false;
            }
            $output .= "</section>";
        }
    }
    function end_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        if ($depth == 0 && $this->column_count > 0) {
            $this->column_count = 0;
        }
        $output .= "</li>";
    }
}

// add mega-menu-columns-# classes
function add_column_number($items, $args) {
    static $column_limit = 3;
    static $post_id = 0;
    static $x_key = 0;
    static $column_count = 0;
    static $li_count = 0;
    $tmp = array();
    foreach($items as $key => $item) {
        if (0 == $item->menu_item_parent) {
            $x_key = $key;
            $post_id = $item->ID;
            $column_count = 0;
            $li_count = 0;
            if (in_array("widget", $item->classes, 1)) {
                $column_count++;
            }
        }
        if ($post_id == $item->menu_item_parent) {
            $li_count++;
            if ($column_count < $column_limit && $li_count == 1) {
                $column_count++;
            }
            if (in_array("break", $item->classes, 1) && $li_count > 1 && $column_count < $column_limit) {
                $column_count++;
            }
            $tmp[$x_key] = $column_count;
        }
    }
    foreach($tmp as $key => $value) {
        $items[$key]->classes[] = sprintf("mega-menu-columns-%d", $value);
    }
    unset($tmp);
    return $items;
};

// add the column classes
add_filter("wp_nav_menu_args", function($args) {
    if ($args["walker"] instanceof megaMenuWalker) {
        add_filter("wp_nav_menu_objects", "add_column_number");
    }
    return $args;
});

// stop the column classes function
add_filter("wp_nav_menu", function( $nav_menu ) {
    remove_filter("wp_nav_menu_objects", "add_column_number");
    return $nav_menu;
});

1
这真是太神奇了,这正是我很久以来一直想要构建的!我不确定如何处理新列的创建,所以我真的很喜欢只在项目上设置类名以创建新列的想法,以及添加小部件区域的能力,真是天才!但是,我在完成的代码中遇到了一些麻烦...它输出正确的HTML,但是我收到此PHP错误... Warning: Missing argument 2 for add_column_number() 您遇到此问题了吗?
JasonDavis 2014年

我不这么认为,在到目前为止我使用过的两个站点上,它似乎都运行良好。我已经更新了上面的代码,以防在实现时有所更改。再试一次,让我知道它是否仍然无法正常工作。我对PHP不太满意,但很乐于尝试和提供帮助:)
JacobTheDev 2014年

1
我要做的就是将其更改function add_column_number($items, $args) {function add_column_number($items) {删除该标记,$args并且对于该更改而言,对我来说效果很好,这很奇怪!感谢共享代码,尽管这正是我很长时间以来所需要的
JasonDavis 2014年

没问题,我知道这样做有多困难,这就是为什么我共享我的完整代码的原因:)很高兴它有所帮助!
JacobTheDev 2014年

Answers:


7

如果我正确理解问题的设置,则可以尝试在过滤器中进行中断小部件类计数wp_nav_menu_objects

这是一个更新的示例,由于额外的调试部分,它进行了扩展:

add_filter( 'wp_nav_menu_objects', 
    function( $items, $args  ) {

        // Only apply this for the 'primary' menu:    
        if( 'primary' !== $args->theme_location ) 
            return $items;

        // Here "x_" means the latest root li (depth 0)
        static $x_pid           = 0;      // post ID of the latest root li (depth 0) 
        static $x_key           = 0;      // array key of the latest root li (depth 0)
        static $x_cols          = 0;      // n breaks or widgets gives n+1 columns  
        static $x_has_dropdown  = false;  // if the latest root li (depth 0) has dropdown

        // Internals:
        $tmp            = array();  
        $debug_string   = '';
        $show_debug     = true;  // Edit this to your needs:

        foreach( $items as $key => $item )
        {
            // Debug:
            $debug                              = array();
            $debug['ID']                        = $item->ID;
            $debug['title']                     = $item->title;
            $debug['key']                       = $key;
            $debug['x_key']                     = $x_key;
            $debug['depth']                     = '';
            $debug['menu_item_parent']          = $item->menu_item_parent;
            $debug['has_widget_class']          = 0;
            $debug['is_depth_1_first_child']    = 0;
            $debug['x_has_dropdown']            = 0;
            $debug['has_break_class']           = 0;
            $debug['x_cols_increase']           = 0;

            // Collect columns increaments:
            $inc = 0;

            // Depth 0:
            if( 0 == $item->menu_item_parent )
            {
                $debug['depth'] = 0;

                // Resets:
                $x_key          = $key;
                $x_pid          = $item->ID;                            
                $x_cols         = 0;
                $x_has_dropdown = false;

                // If widget class exists:
                if( in_array( 'widget', $item->classes, 1 ) )
                {
                    $debug['has_widget_class'] = '1';
                    $inc++; 
                }       
            }

            // Depth 1:
            if( $x_pid == $item->menu_item_parent )
            {   
                $debug['depth'] = 1;

                // Increase the columns count for an existing dropdown:
                if( ! $x_has_dropdown )
                {
                    $inc++;
                    $x_has_dropdown = true;
                }

                // Check for the 'break' class: 
                if( in_array( 'break', $item->classes, 1 ) )
                {
                    $debug['x_has_break_class'] = 1;

                    // First li child:
                    if( $x_key+1 == $key+0 )
                    {
                        $debug['is_depth_1_first_child'] = 1;
                    }
                    else
                    {
                        $debug['is_depth_1_first_child'] = 0;
                        $inc++; 
                    }
                }

                $t[$x_key] = $x_cols;
            }           

            $debug['x_has_dropdown'] = (int) $x_has_dropdown;

            // Increase the columns count:
            $debug['x_cols_increase'] = $inc;           
            $x_cols += $inc;
            $debug['x_cols'] = $x_cols;

            // Collect the debug:
            $debug_string .= print_r( $debug, 1 );
        } // end foreach

        // Show debug info:
        if( $show_debug ) 
            printf( "<!-- debug: %s -->", $debug_string );

        // Insert the new 'mega menu' class to the corresponding menu object:
        foreach( $t as $key => $value )
        {
            $items[$key]->classes[] = sprintf( 'mega-menu-columns-%d', $value );
        }

        return $items;

    }
, PHP_INT_MAX, 2 );

使用您当前的菜单树,我得到以下调试信息:

<!-- debug: Array
(
    [ID] => 3316
    [title] => About Us
    [key] => 1
    [x_key] => 0
    [depth] => 0
    [menu_item_parent] => 0
    [has_widget_class] => 1
    [is_depth_1_first_child] => 0
    [x_has_dropdown] => 0
    [has_break_class] => 0
    [x_cols_increase] => 1
    [x_cols] => 1
)
Array
(
    [ID] => 3317
    [title] => Company Profile
    [key] => 2
    [x_key] => 1
    [depth] => 1
    [menu_item_parent] => 3316
    [has_widget_class] => 0
    [is_depth_1_first_child] => 1
    [x_has_dropdown] => 1
    [has_break_class] => 0
    [x_cols_increase] => 1
    [x_has_break_class] => 1
    [x_cols] => 2
)
Array
(
    [ID] => 3318
    [title] => Our Team
    [key] => 3
    [x_key] => 1
    [depth] => 
    [menu_item_parent] => 3317
    [has_widget_class] => 0
    [is_depth_1_first_child] => 0
    [x_has_dropdown] => 1
    [has_break_class] => 0
    [x_cols_increase] => 0
    [x_cols] => 2
)
Array
(
    [ID] => 3319
    [title] => Leadership Team
    [key] => 4
    [x_key] => 1
    [depth] => 1
    [menu_item_parent] => 3316
    [has_widget_class] => 0
    [is_depth_1_first_child] => 0
    [x_has_dropdown] => 1
    [has_break_class] => 0
    [x_cols_increase] => 0
    [x_cols] => 2
)
Array
(
    [ID] => 3320
    [title] => Professional Affiliations
    [key] => 5
    [x_key] => 1
    [depth] => 1
    [menu_item_parent] => 3316
    [has_widget_class] => 0
    [is_depth_1_first_child] => 0
    [x_has_dropdown] => 1
    [has_break_class] => 0
    [x_cols_increase] => 0
    [x_cols] => 2
)
Array
(
    [ID] => 3321
    [title] => Clients
    [key] => 6
    [x_key] => 1
    [depth] => 1
    [menu_item_parent] => 3316
    [has_widget_class] => 0
    [is_depth_1_first_child] => 0
    [x_has_dropdown] => 1
    [has_break_class] => 0
    [x_cols_increase] => 1
    [x_has_break_class] => 1
    [x_cols] => 3
)
Array
(
    [ID] => 3322
    [title] => Partnerships
    [key] => 7
    [x_key] => 1
    [depth] => 1
    [menu_item_parent] => 3316
    [has_widget_class] => 0
    [is_depth_1_first_child] => 0
    [x_has_dropdown] => 1
    [has_break_class] => 0
    [x_cols_increase] => 0
    [x_cols] => 3
)
 -->

如果要检查walker对象是否属于此类megaMenuWalker,可以使用:

if( ! is_object( $args->walker ) || ! is_a( $args->walker, 'megaMenuWalker' ) )
    return $items;

代替

if( 'primary' !== $args->theme_location ) 
            return $items;

我希望这有帮助。


奇怪的是,这将输出1作为数字。请参阅hfracquetandfitness.myweblinx.net(检查顶部导航中的第一个li)。编辑-我想我知道为什么。Break被添加到直接子<li>元素中,而不是current中<li>。它需要检查它是一个直接子级,而不是第一个具有该子级的子级break
JacobTheDev 2014年

我更新了答案,输入错误(&&而不是||)。
birgire 2014年

嗯,这有所帮助,但是我认为当前列表项的类为,这很重要break。实际上,需要计算直系子女是否具有的类break,而不是本身,并且要排除该子女li中的第一个子女ul,如果这是有意义的话。
JacobTheDev 2014年

我假设根<li>项目在深度0,然后计算<li>深度处子项目的break / widget类1。我想我应该开始$x_cols1代替0,因为n中断给n+1列。
birgire

1
别客气。我用一个示例更新了答案,该示例如何检查Walker类而不是主题位置。祝您项目顺利。
birgire 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.