1

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!

2
  • Do you want to do this inside menu (as in Walker class) or outside (as in find current page in menu and get its menu parent)?
    – Rarst
    Mar 19, 2014 at 18:54
  • Outside of the menu. yes as in find current page in menu and get its menu parent, exactly
    – Malibur
    Mar 19, 2014 at 18:56

1 Answer 1

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;
}
3
  • That was exactly what i was after! Amazing. Thank you so much.
    – Malibur
    Mar 20, 2014 at 10:00
  • Do you think it is possible to use a theme location instead of the menu ID ?
    – Malibur
    Mar 20, 2014 at 13:10
  • @MaltheMilthers probably, but you'll have to figure out how to get assigned menu
    – Rarst
    Mar 20, 2014 at 13:13

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.