Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I wanna use 'depth' in a sidebar menu to only display the first child page, and I wonder where in my code I should insert depth? I wanna be able to only show the first child page and not all child pages. I have tried to insert 'depth' under this if conditon

if ( $item->current_item_ancestor && $item->menu_item_parent == '0' )
{
    $last_parent = $item,
    'depth' => 1
}

/* ------------------------------------------------------------------- */

function myproject_nav_menu_objects_start_in( $sorted_menu_items, $args )
{

   switch ( $args->menu_id )
   {
       case 'sidebar-menu' :

       $current = false;
       $last_parent = false;
       $menu = array();

       foreach( $sorted_menu_items as $item )
       {
           if ( $item->current_item_ancestor && $item->menu_item_parent == '0' )
               $last_parent = $item;

           if ( $item->current )
               $current = $item;
       }

       if ( $current ) 
       {
           $keys = array();
           $last_parent = ( ! $last_parent ) ? $current : $last_parent;

           $children = _myproject_submenu_get_children_ids( $last_parent->ID, $sorted_menu_items );

           foreach ( $sorted_menu_items as $key => $item ) 
           {
               if ( ! in_array( $item->ID, $children ) )
                   unset( $sorted_menu_items[$key] );
           }

       }
       else
       {
           $sorted_menu_items = array();
       }

       break;

   }
   return $sorted_menu_items;
}
add_filter( 'wp_nav_menu_objects', 'myproject_nav_menu_objects_start_in', 10, 2 );
share|improve this question

migrated from stackoverflow.com Nov 12 '13 at 0:32

This question came from our site for professional and enthusiast programmers.

1 Answer 1

On recursive methods, I usually add a $depth parameter:

function my_function($depth = -1)
{
    if ($depth === 0) {
        return array(); // or any other value insisting an empty or false result
    }
    // do something
    $result = array();
    while ($some_condition) {
        $result = array_merge($result, my_function($depth - 1)); // decrease $depth value
    }
    // maybe do something more
    return $result;
}

When calling my_function() without a $depth parameter, there won't be any restriction in the depth. But if you provide a $depth value, it'll stop recursion when the $depth value is zero.

Don't use $depth-- in a loop. $depth - 1 is the correct way.

share|improve this answer
    
Ok, Im gonna test your code a little bit. –  LoveWP Oct 28 '13 at 12:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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