getting parent page id when using custom menu.

Im using custom menus to display a menu using wp_nav_menu(). I want to get the_content() of the parent in the menu, without setting it as a parent page in pages. Is there a way to get the parent id (in php). I can see that the wp_nav_menu gives the parent item a special class name, so i believe i should be able to retrieve that items id, and do something with it before the page loads. Is this possible?

Thanks!

Related posts

Leave a Reply

1 comment

  1. Not sure if this is robust enough, but it shows basic traversal through menu to look for current post first then for its menu parent:

    /**
     * @param mixed $menu
     * @param int   $post_id
     *
     * @return WP_Post|bool
     */
    function get_menu_parent( $menu, $post_id = null ) {
    
        $post_id        = $post_id ? : get_the_ID();
        $menu_items     = wp_get_nav_menu_items( $menu );
        $parent_item_id = wp_filter_object_list( $menu_items, array( 'object_id' => $post_id ), 'and', 'menu_item_parent' );
    
        if ( ! empty( $parent_item_id ) ) {
            $parent_item_id = array_shift( $parent_item_id );
            $parent_post_id = wp_filter_object_list( $menu_items, array( 'ID' => $parent_item_id ), 'and', 'object_id' );
    
            if ( ! empty( $parent_post_id ) ) {
                $parent_post_id = array_shift( $parent_post_id );
    
                return get_post( $parent_post_id );
            }
        }
    
        return false;
    }