0

I'm trying to show a WordPress menu based on the value of a cookie. In my example, I'm using cookies to define the geographical region that the user wants to view. (I'm still working on this part so I'm manually defining it during development.) Based on this, I want to use either menu1 or menu2. Currently I'm using the following code:

function pstv_set_cookie() {
    $expire=time()+60*60*24*30;
    setcookie("region", "1", $expire);
}
add_action( 'init', 'pstv_set_cookie');

    if ($_COOKIE[$region] = "1"){ 
        //Use Menu 1
        wp_nav_menu( array('menu' => 'menu1' ));
        //wp_nav_menu( array( 'theme_location' => 'menu1' ) );

    }elseif ($_COOKIE[$region] = "2"){ 
        //Use Menu 2
        wp_nav_menu( array('menu' => 'menu2' ));
        //wp_nav_menu( array( 'theme_location' => 'menu2' ) );
    }  

This works almost as expected, but it spits out the menu HTML before anything else.

Where do I add my coded to hook into the WordPress menu?

Note: I've tried:

wp_nav_menu( array('menu' => 'menu2' ));  AND
wp_nav_menu( array( 'theme_location' => 'menu2' ) );

(I'm not too sure of the difference.) Thanks in advance

4

1 回答 1

0

wp_nav_menu 在现场显示一个导航菜单,你正在使用一个 init 钩子,它在其他任何东西之前运行,就像你想象的那样。

任何一个:

过滤器示例(未测试):

add_filter('wp_nav_menu_args', 'my_wp_nav_menu_args_filter');
function my_wp_nav_menu_args_filter($args = array()) {
  $args['menu'] = 'menu1';
  return $args;
}
于 2013-08-26T11:48:59.593 回答