0
votes

I've created a custom field for Menu Items.

I'm using the field to allow the user to add onClick events.

For some reason I can't get the value when I call get_field.

This is my test code:

function nav_analytics_field(  $atts, $item, $args ) {

    foreach( $item as &$link ) {

        $event_code = get_field('ga_event');

        if( $event_code ) {
        $atts['onClick'] = $event_code;
        } else {
        $atts['data-event'] = 'no-event';
    }
    } // end foreach

    return $atts ;

}

The loop adds an onClick attribute to each menu item.

My filtering is clearing working: for each menu item I am getting the output of the 'else' condition. However, this happens whether field data exists or not.

This indicates that $event_code isn't being populated by get_field().

So... how do I actually get the field?

1

1 Answers

1
votes

You just need to pass the ID of the current nav item to get_field(), otherwise it's defaulting to the current Post ID (where it's basically guaranteed to return false), which for your code I believe is this:

 $event_code = get_field( 'ga_event', $link );

if not, it's probably an attribute/property of $link