Skip to content

Instantly share code, notes, and snippets.

@danlapteacru
Created May 16, 2024 11:40
Show Gist options
  • Save danlapteacru/e694b31c81012e69af67ad7ce7ff2296 to your computer and use it in GitHub Desktop.
Save danlapteacru/e694b31c81012e69af67ad7ce7ff2296 to your computer and use it in GitHub Desktop.
ACF Menu Depth Rule
<?php
declare(strict_types=1);
use WP_Screen;
/**
* Class MenuDepth
*
* This class is used to define a custom rule for Advanced Custom Fields (ACF) plugin.
* The rule is based on the depth of a menu item in a WordPress menu.
*
* @package App\Plugins\AdvancedCustomFields\Rules
*/
class AcfMenuDepth
{
/**
* MenuDepth constructor.
*
* The constructor adds the custom rule to ACF's rule types, rule values, and rule match filters.
*/
public function __construct()
{
add_filter('acf/location/rule_types', [$this, 'getRuleTypes']);
add_filter('acf/location/rule_values/menu_level', [$this, 'getRuleValues']);
add_filter('acf/location/rule_match/menu_level', [$this, 'getRuleMatch'], 10, 3);
}
/**
* Get rule types.
*
* This method adds the custom rule to ACF's rule types.
*
* @param array $choices Existing rule types.
* @return array Modified rule types.
*/
public function getRuleTypes(array $choices): array
{
$choices['Menu']['menu_level'] = __('Menu Depth', 'sage');
return $choices;
}
/**
* Get rule values.
*
* This method defines the possible values for the custom rule.
*
* @param array $choices Existing rule values.
* @return array Modified rule values.
*/
public function getRuleValues(array $choices): array
{
return range(0, 9);
}
/**
* Get rule match.
*
* This method checks if the custom rule matches the current context.
*
* @param bool $match
* @param array $rule
* @param array $options
* @return bool
*/
public function getRuleMatch(bool $match, array $rule, array $options): bool
{
$current_screen = get_current_screen();
if (
! $current_screen instanceof WP_Screen
|| 'nav-menus' !== $current_screen->base
|| '==' !== $rule['operator']
) {
return $match;
}
return $options['nav_menu_item_depth'] === (int) $rule['value'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment