Skip to content

Commit

Permalink
Fix menuItems language filtering
Browse files Browse the repository at this point in the history
For wp-graphql v1.26 and later
  • Loading branch information
esamattis committed May 21, 2024
1 parent 86d0303 commit 9dba3e9
Showing 1 changed file with 16 additions and 41 deletions.
57 changes: 16 additions & 41 deletions src/MenuItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -30,52 +18,39 @@ 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
function __filter_graphql_menu_item_connection_args(
array $args,
$unfiltered
) {
if (!($resolver instanceof MenuItemConnectionResolver)) {
return $query_args;
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']
);

// 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);
// Ex. TOP_MENU -> TOP_MENU___fi
$args['where']['location'] .= '___' . $lang;

return $resolver->get_query_args();
return $args;
}

/**
Expand Down

0 comments on commit 9dba3e9

Please sign in to comment.