Skip to content

Instantly share code, notes, and snippets.

@TeemuSuoranta
Created March 11, 2021 13:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TeemuSuoranta/8652ac34c085ec704e3559636b8f26f7 to your computer and use it in GitHub Desktop.
Save TeemuSuoranta/8652ac34c085ec704e3559636b8f26f7 to your computer and use it in GitHub Desktop.
Fix ACF menu location rules to work on all Polylang locales
<?php
/**
* Fix ACF menu location rules to work on all Polylang locales
*
* Polylang registers localized variations to menu locations and by default
* ACF cannot hook to all of them unless they are manually all picked.
* Polylang separates location with three undescores (eaxmple: primary___en).
*
* This hook automatically applies all menu location rules to all languages.
* Works for both nav_menu and nav_menu_item related fields.
*
* @param bool $match weather this view is match for this field group
* @param array $rule matching ruleset
* @param array $options info on current view
* @param array $field_group registered fields
*
* @return bool $match
*/
add_filter('acf/location/rule_match', function ($match, $rule, $options, $field_group) {
if (is_array($rule) && in_array($rule['param'], ['nav_menu', 'nav_menu_item']) && strstr($rule['value'], 'location/')) {
$match_menu_position = str_replace('location/', '', $rule['value']);
$current_menu_id = 0;
if ($rule['param'] == 'nav_menu_item' && isset($options['nav_menu_item_id']) && !empty($options['nav_menu_item_id'])) {
$nav_menus = wp_get_post_terms($options['nav_menu_item_id'], 'nav_menu', ['fields' => 'ids']);
if (is_array($nav_menus) && isset($nav_menus[0])) {
$current_menu_id = (int) $nav_menus[0];
}
} elseif ($rule['param'] == 'nav_menu' && isset($options['nav_menu']) && !empty($options['nav_menu'])) {
$current_menu_id = (int) $options['nav_menu'];
}
if (is_array($options) && !empty($current_menu_id)) {
$menus = (array) get_nav_menu_locations();
foreach ($menus as $menu_position => $menu_id) {
$menu_position_parts = explode('___', $menu_position);
if ($menu_id == $current_menu_id && $menu_position_parts[0] == $match_menu_position) {
return true;
}
}
}
}
return $match;
}, 10, 4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment