How can I list the siblings of the current page/post based on a menu structure in wordpress

I have been strubbling with this menu problem for a while now and can’t seem to get the answer I am looking for. I would like to display all the “sibling” menu items only on the sidebar. So if I have the following menu structure;
– 1
— 1.1
— 1.2
— 1.3
— 1.4
— 1.5
– 2
— 2.1 …….
— 2.5
– 3

if the user is on the page/post 1.3, I would like to list

Read More

1.1

1.2

1.3

1.4

1.5

..only. Currently, I am able to list the siblings with a function I have, but only if I hard-code the title of the page 1 which is the ancestor of 1.3. I would like to get the name of the ancestor of 1.3 dynamically and not have to hard-code it. How can I ;

  1. dynamically get the immediate ancestor of the page I am in?

2.If question 1 is not possible, how can i get the siblings Only?

Below is the code I have;

  1. This code goes to the functions.php in wordpress;

    <?php
           add_filter( 'wp_nav_menu_objects', 'submenu_limit', 10, 2 );
    
           function submenu_limit( $items, $args ) {
    
                if ( empty($args->submenu) )
                    return $items;
                $arguments = wp_filter_object_list( $items, array( 'title' => $args->submenu ), 'and', 'ID' );
                $parent_id = array_pop( $arguments  );
                $children  = submenu_get_children_ids( $parent_id, $items );
    
                foreach ( $items as $key => $item ) {
    
                    if ( ! in_array( $item->ID, $children ) )
                        unset($items[$key]);
                }
    
               return $items;
            }
    
          function submenu_get_children_ids( $id, $items ) {
    
              $ids = wp_filter_object_list( $items, array( 'menu_item_parent' => $id ), 'and', 'ID' );
    
          foreach ( $ids as $id ) {
    
          $ids = array_merge( $ids, submenu_get_children_ids( $id, $items ) );
           }
    
          return $ids;
         }
       ?>
    

    Then below is the function I am using to get the submenuitems. As you can see, I have hard-coded the parent/ancestor (‘Business & Commercial’) of my current post as is in the menu named “Topest Menu”;

    <?php  
        //code that goes to the sidebar.php
        $args = array(
            'menu'    => 'Topest menu',
            'submenu' => 'Business & Commercial',
        );
    
        wp_nav_menu( $args );
    

    ?>

Related posts

Leave a Reply