Home > php > How to display conditional-content if wp_nav_menu( $args ) retruns something

How to display conditional-content if wp_nav_menu( $args ) retruns something

March 30Hits:1
Advertisement

I have a sidebar that displays child links of the current page (using this solotuin by http://wordpress.stackexchange.com/a/2809/27414) which works perfectly.

If there is child links to be displayed in the side bar I would like to give it a heading such as "Also is this section".

I have tried the following which didn't work:

if (wp_nav_menu( $args )){     echo "Also in this section"; } 

Thanks

Answers

Use has_nav_menu to check if a location has been assigned a menu or not

<?php
if ( has_nav_menu( $location ) ) {
     echo "Also in this section";
}
?>

http://codex.wordpress.org/Function_Reference/has_nav_menu

For more advanced checks you'll need to do a call to wp_get_nav_menu_items and process the items it returns to see if any of them are children.

Here's an example outputting a menu that shows how to use its output:

// Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu)
// This code based on wp_nav_menu's code to get Menu ID from menu slug

$menu_name = 'custom_menu_slug';

if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
    $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );

    $menu_items = wp_get_nav_menu_items($menu->term_id);

    $menu_list = '<ul id="menu-' . $menu_name . '">';

    foreach ( (array) $menu_items as $key => $menu_item ) {
        $title = $menu_item->title;
        $url = $menu_item->url;
        $menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
    }
    $menu_list .= '</ul>';
} else {
    $menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
}
// $menu_list now ready to output

A vital thing to note is that a nav menu is made out of nav menu items, and these menu items are custom post types. Use the parent child association to determine the depth, just as you would with pages and posts

Related Articles

Copyright (C) 2018 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.597 s.