Getting parent object_id of child menu items in WordPress menu

I am building a menu for a client that grabs custom field data from the top level menu item's pages and adds data-color to that menu item. I have that part working no problem.

The issue I'm having is applying that data-color from the top level item to the child menu items. Since the child menu items aren't necessarily child posts/pages of the top level pages I can't use $item-post_parent.

I'm a little stuck at this point on my next move. Here's the code block so far.

function data_attribs_menu( $atts, $item, $args ) {
    // check if ACF exists
    if( class_exists('acf') ) {     
        $page_section = get_field( 'page_section', $item-object_id );
        $parent_page_section = get_field( 'page_section', $item-post_parent );

        if( $args-theme_location == 'header-menu' ) {
            if( $item-menu_item_parent == 0 ) {
                $atts['data-color'] = $page_section;
            } else {
                $atts['data-color'] = $parent_page_section;
            }
        }
    }
    return $atts;
}
add_filter('nav_menu_link_attributes', 'data_attribs_menu', 10, 3);

Is there a way to grab the parent's object_id for submenu items?

Here's a video of how the menu is currently interacting.

Topic sub-menu menus Wordpress

Category Web


I made 2 mistakes in my comment.
try rather this code

function data_attribs_menu( $atts, $item, $args ) {
    // check if ACF exists
    if( class_exists('acf') ) {     

        $page_section = get_field( 'page_section', $item->object_id );

        if( $args->theme_location == 'header-menu' ) {
            if( $item->menu_item_parent == 0 ) {
                $atts['data-color'] = $page_section;
            } else {
                $parentItem = get_post($item->menu_item_parent);
                $parent_page_section = get_field( 'page_section', $parentItem->_menu_item_object_id);

                $atts['data-color'] = $parent_page_section;
            }
        }

    }

    return $atts;
}
add_filter('nav_menu_link_attributes', 'data_attribs_menu', 10, 3);

this code only works when there is 2 levels of menu and according the example in the question, it's what you need.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.