0
votes

I have this simple snippet in my header displaying the site's Main Menu:

<?php wp_nav_menu( array( 
    'theme_location' => 'main-menu',
    'container'=> false ) ); 
?>

The menu displays the site's pages. Each page has a custom field added with Advanced Custom Fields called text_color. It's a color picker that let's me choose which color the menu item should have when hovering on it. I would like to have this field in the settings for the page itself, and not as a field added to the menu settings of Wordpress.

The hovering effect is created with a data attribute called data-hover. I then listen for mouseover and mouseleave events through JavaScript on each menu item, changing the text color of the menu item upon hovering, to the color code that's in the data-hover.

Since each menu item is connected to a page, I would like to be able to reach the page loop for each menu item, adding this data-hover to each anchor link in the menu item. Is this possible?

2

2 Answers

1
votes

Add this to your functions.php in theme

add_filter( 'nav_menu_link_attributes', 'add_custom_data_atts_to_nav', 10, 4 );
function add_custom_data_atts_to_nav( $atts, $item, $args ) {

$atts['data-hover'] = $item->title;
return $atts;}

hope this will help!

0
votes

Not sure if this will work

But adding a class according to your ACF field could be possible if you get the items ID.

So something like this

function add_class_to_menu_item_by_acf($sorted_menu_objects, $args) {
    $theme_location = 'main-menu';  // Name, ID, or Slug of the target menu location



    if ($args->theme_location == $theme_location) {
        foreach ($sorted_menu_objects as $key => $menu_object) {
                //Get the menu objects post/page id - Check the object to see if this is the correct variable.
                $objectID = $menu_object->object_id;
                //Get the field
                $fieldColor = get_field('text_color', $objectID);
                if($fieldColor){
                    $menu_object->classes[] = "text_color_".$fieldColor;
                }

        }
    }

    return $sorted_menu_objects;
}

add_filter('wp_nav_menu_objects', 'add_class_to_menu_item_by_acf', 10, 2);

Again, I haven't tested this - but it might lead you on the right track?