1

I need to add a conditional menu item such as "/at" or "/de" or "/ch" in the wp_nav_menu. Since the link is conditional (based on the country the website is being viewed), it can't be added from the backend but instead has to be hardcoded.

How do I add this new conditional link at the end of what the wp_nav_menu is populating? Thank you.

2

This is what worked for me (based on this).. hope it will be helpful for others too..

add_filter( 'wp_nav_menu_items','primary_navigation', 10, 2 );
function primary_navigation( $items, $args ) {
    if( $args->theme_location == 'primary_navigation' )  {
        if ( ! isset( $_SESSION['menu_country'] ) ) {
            $country = json_decode( file_get_contents(
               "http://freegeoip.net/json/" . esc_url( $_SERVER['REMOTE_ADDR'] )
            ) );

            $_SESSION['menu_country'] = strtolower( $country->country_code );   
        }

       $items .=  '<li class="menu-produkte"><a href="/' .
          esc_url( $_SESSION['menu_country'] ) .'/shop">Produkte</a></li>';
    }
    return $items;
}
0

You could also potentially do this with items_wrap if you wanted to. Haven't tested this, but maybe something like:

if ( !isset( $_SESSION['menu_country'] ) ) {
    $country = json_decode( file_get_contents(
     "http://freegeoip.net/json/" . esc_url( $_SERVER['REMOTE_ADDR'] )
    ) );

    $_SESSION['menu_country'] = strtolower( $country->country_code );

    $item = '<li class="menu-produkte"><a href="/' .
        esc_url( $_SESSION['menu_country'] ) . '/shop">Produkte</a></li>';
}
else {
    $item = null;
}
wp_nav_menu( array(
    'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s' . $item . '</ul>',
) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.