From 7005ceabd04c97ca5fafb8b9a9e304869ee1cff7 Mon Sep 17 00:00:00 2001 From: Esa-Matti Suuronen Date: Tue, 21 May 2024 12:55:08 +0300 Subject: [PATCH] Fix menuItems language filtering For wp-graphql v1.26 and later --- src/MenuItem.php | 55 ++++++++++++------------------------------------ 1 file changed, 14 insertions(+), 41 deletions(-) diff --git a/src/MenuItem.php b/src/MenuItem.php index 3e790c2..55a84f5 100644 --- a/src/MenuItem.php +++ b/src/MenuItem.php @@ -7,18 +7,6 @@ class MenuItem { - /** - * Convert menu location to match the one generated by Polylang - * - * Ex. TOP_MENU -> TOP_MENU___fi - */ - static function translate_menu_location( - string $location, - string $language - ): string { - return "${location}___${language}"; - } - function init() { $this->create_nav_menu_locations(); @@ -30,52 +18,37 @@ function init() 0 ); + // https://github.com/wp-graphql/wp-graphql/blob/release/v1.26.0/src/Data/Connection/MenuItemConnectionResolver.php#L107 add_filter( - 'graphql_connection_query_args', - [$this, '__filter_graphql_connection_query_args'], + 'graphql_menu_item_connection_args', + [$this, '__filter_graphql_menu_item_connection_args'], 10, 2 ); } - function __filter_graphql_connection_query_args( - array $query_args, - AbstractConnectionResolver $resolver - ) { - if (!($resolver instanceof MenuItemConnectionResolver)) { - return $query_args; + function __filter_graphql_menu_item_connection_args(array $args, $unfiltered) { + if (!isset($args['where']['location'])) { + return $args; } - $args = $resolver->getArgs(); + $lang = $args['where']['language'] ?? null; - if (!isset($args['where']['language'])) { - return $query_args; - } - - if (!isset($args['where']['location'])) { - return $query_args; + if (!$lang) { + return $args; } // Required only when using other than the default language because the // menu location for the default language is the original location - if (pll_default_language('slug') === $args['where']['language']) { - return $query_args; + if (pll_default_language('slug') === $lang) { + return $args; } - // Update the 'location' arg to use translated location - $args['where']['location'] = self::translate_menu_location( - $args['where']['location'], - $args['where']['language'] - ); + // Ex. TOP_MENU -> TOP_MENU___fi + $args['where']['location'] .= '___' . $lang; - // XXX. This is a hack. Modify the protected "args" so we can re-execute - // the get_query_args method with the new "location" arg - $ref = new \ReflectionObject($resolver); - $args_prop = $ref->getProperty('args'); - $args_prop->setAccessible(true); - $args_prop->setValue($resolver, $args); - return $resolver->get_query_args(); + return $args; } /**