Support

Account

Home Forums Feature Requests Conditional Logic on Menu Item

Solving

Conditional Logic on Menu Item

  • Hi there

    I’m trying to add some fields to a menu item in a specific depth.

    ACF makes it possible to add fields to the Menu as a whole (useful for options on a nav) or on every menu item (but on all). The conditions which are provided are Menu Location or Menu Name.

    I’m questioning if there is a possibility to add a custom condition to filter by menu item depth? Meaning that fields are applied only when the the nav item is a sub item. I know that this involves some JS, but since some versions we’ve got this possibilities to filter in this way.

  • Actually, this would likely mean adding a custom location rule https://www.advancedcustomfields.com/resources/custom-location-rules/, but beyond that I would not know how to accomplish it.

  • This should work:

    
    <?php
    
    add_filter('acf/location/rule_types', 'acf_location_rules_types');
    
    function acf_location_rules_types($choices)
    {
        $choices['Menu']['menu_level'] = 'NĂ­vel do Menu';
    
        return $choices;
    }
    
    add_filter('acf/location/rule_values/menu_level', 'acf_location_rule_values_level');
    
    function acf_location_rule_values_level($choices)
    {
        $choices[0] = '0';
        $choices[1] = '1';
    
        return $choices;
    }
    
    add_filter('acf/location/rule_match/menu_level', 'acf_location_rule_match_level', 10, 4);
    function acf_location_rule_match_level($match, $rule, $options, $field_group)
    {
        if ($rule['operator'] == "==") {
            $match = ($options['nav_menu_item_depth'] == $rule['value']);
        }
    
        return $match;
    }
    
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.