Site icon Hip-Hop Website Design and Development

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.