最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugin development - Get Current Menu Location inside Nav_Walker

programmeradmin0浏览0评论

How can I retrieve the current menu location (as registered with register_nav_menus) from inside a nav-walker class?

eg:

<?php

class Special_Nav_Walker extends Walker_Nav_Menu {

    // How can I get `special_menu` here, when the walker is applied to the menu (see below)

}

wp_nav_menu(
    [
        'theme_location'    => 'special_menu',
        'walker'            => new Special_Nav_Walker(),
    ]
);

How can I retrieve the current menu location (as registered with register_nav_menus) from inside a nav-walker class?

eg:

<?php

class Special_Nav_Walker extends Walker_Nav_Menu {

    // How can I get `special_menu` here, when the walker is applied to the menu (see below)

}

wp_nav_menu(
    [
        'theme_location'    => 'special_menu',
        'walker'            => new Special_Nav_Walker(),
    ]
);

Share Improve this question asked Sep 19, 2019 at 19:03 admcfajnadmcfajn 1,3262 gold badges13 silver badges30 bronze badges 2
  • What are you trying to accomplish? That information is passed into the functions of the Walker_Nav_Menu – czerspalace Commented Sep 19, 2019 at 20:47
  • I was considering using menu-locations specific conditionals in a feature I was building. Just wasn't sure where to find the info & figured it'd make a good question because I wasn't able to find a quick answer anywhere. – admcfajn Commented Sep 20, 2019 at 16:25
Add a comment  | 

1 Answer 1

Reset to default 1

There's no constructor, so it's not available as a property of the class, but each method in the class receives the arguments passed to wp_nav_menu() as an object. For example, start_lvl():

/**
 * Starts the list before the elements are added.
 *
 * @since 3.0.0
 *
 * @see Walker::start_lvl()
 *
 * @param string   $output Used to append additional content (passed by reference).
 * @param int      $depth  Depth of menu item. Used for padding.
 * @param stdClass $args   An object of wp_nav_menu() arguments.
 */
public function start_lvl( &$output, $depth = 0, $args = array() ) {
    if ( 'special_menu' === $args->theme_location ) {
        // Do something.
    }
}

Yes, the default value for $args is an array, but nav walkers receives it as an object, for some reason.

The other methods also make the arguments available, but not necessarily as the 3rd argument. You'll need to see which parameters are passed to each method, but you need to do that when extending a class anyway.

发布评论

评论列表(0)

  1. 暂无评论