GithubHelp home page GithubHelp logo

valu-digital / wp-graphql-polylang Goto Github PK

View Code? Open in Web Editor NEW
123.0 3.0 20.0 417 KB

WPGraphQL Polylang Extension for WordPress

Home Page: https://packagist.org/packages/valu/wp-graphql-polylang

License: GNU General Public License v2.0

PHP 93.98% Shell 4.79% Dockerfile 1.22%
wordpress-plugin graphql polylang wpml

wp-graphql-polylang's Introduction

WPGraphQL Polylang Extension

Extend WPGraphQL schema with language data from the Polylang plugin.

Features

For posts and terms (custom ones too!)

  • Adds language and translations fields
  • Filter with a language where argument
  • Set the language on create and update mutations
  • Show all translations in the api by default
    • Polylang patches the WP Query to only list items with the current default language. This plugin reverts that for the GraphQL api
  • ACF Options Pages support

Root queries

  • defaultLanguage get the current default language
  • languages list all configured languages

Menu

  • Filter menu items by language

For details please refer to the generated docs in GraphiQL.

Example

Example showing all features

query PolylangExample {
    # Filter pages by language. If not set it defaults to ALL
    pages(where: { language: EN }) {
        nodes {
            title

            # Get language of each page
            language {
                code # Language code
                name # Human readable name of the language
            }

            # Get links to the translates versions of each page
            # This is an array of post objects
            translations {
                title
                link
                language {
                    code
                }
            }
        }
    }

    # Taxonomies such as tags can be filtered like post objects
    tags(where: { language: EN }) {
        nodes {
            name
            language {
                code
                name
            }
        }
    }

    # Get translated version of a given menu
    menuItems(where: { language: EN, location: FOOTER_MENU }) {
        nodes {
            url
        }
    }

    # Get the default language
    defaultLanguage {
        name
        code
    }

    # Get all configured languages
    languages {
        name
        code
    }

    # Get translations for ACF Options Pages.
    # See the section in the README.
    siteSettings(language: EN) {
        siteSettings {
            footerTitle
        }
    }
}

Requirements

  • PHP 7.2 or later
  • WPGraphQL 0.13.x or later
  • Polylang 2.6.5 or later
    • The free version is enough
    • If you get the PRO version the pro features such as translated slugs will work too

Installation

If you use composer you can install it from Packagist

composer require valu/wp-graphql-polylang

Otherwise you can clone it from Github to your plugins using the stable branch

cd wp-content/plugins
git clone --branch stable https://github.com/valu-digital/wp-graphql-polylang.git

ACF Options Pages

In addition to WPGraphQL and Polylang plugins you'll need these plugins too

You can install the free plugins using Composer. You'll need to have the WordPress Packagist repository enabled.

composer require wp-graphql/wp-graphql-acf wpackagist-plugin/acf-options-for-polylang

When registering the Options Page you must pass in show_in_graphql and graphql_field_name arguments.

acf_add_options_page([
    'page_title' => __('Site settings', 'theme'),
    'menu_title' => __('Site settings', 'theme'),
    'menu_slug' => 'site-settings',
    'capability' => 'manage_options',
    'redirect' => false,
    'show_in_graphql' => true,
    'graphql_field_name' => 'siteSettings'
]);

Slack

You can find us from the WPGraphQL Slack on the #polylang channel.

WPML

But I'm using WPML?!

There's rburgst/wp-graphql-wpml.

Or you might want to checkout migration docs

https://polylang.pro/how-to-switch-from-wpml-to-polylang/

Contributing

Checkout CONTRIBUTING.md

wp-graphql-polylang's People

Contributors

davidfaber avatar esamattis avatar huesy avatar jasonbahl avatar philjohnson avatar simptheshrimp2 avatar tpaananen79 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

wp-graphql-polylang's Issues

Introducing language specific isFrontPage

My suggestion is to introduce some identifier for the frontpage of each language.

This would help to identify the Homepage of each language on the StaticSiteGeneration-Side, so one can adjust the paths to be /, /en/, /de/ without the title like /en/home`.

Example Query could be:

query MyQuery {
  pages(where: {parent: null}, first: 100) {
    nodes {
      title
      uri
      language {
        isFrontPage
      }
    }
  }
}

@epeli suggested to do something like this in the core wp-graphql:

return apply_filters( 'graphql_post_is_front_page', $post->ID === get_option('page_on_front'), $post);

And wp-graphql-polylang could extend that by returning true for all translated front pages too.

When using language codes/slugs like 'nl-nl' the graphql return an enum error

Some websites need a double language code/slug.
nl-nl
nl-en
be-nl
be-fr
be-en

The graphql does not open when a language is configured this way.
it gives this php error en remains loading endlesly

Names must only contain [_a-zA-Z0-9] but "NL-NL" does not.

easy replicable by simply changing the code name of a language

It looks like a minor validation issue, but i can't trace it in the php

Polylang language switcher overrules language argument on pages field, when logged in as admin.

I have created two languages in Polylang.
I have a query with the pages(where: {language: ALL}) field set.
When I'm logged in as an admin and select a language, in the language switcher in the top toolbar, in the controlpanel, the pages field only return pages from the actual language, selected in the language switcher.

I would have excepted the query to return pages from both languages, when the argument for language is set to ALL.
If I'm logged out of Wordpress, the query return the pages for all languages as excepted. It only happens when I'm logged in.

I'm using Wordpress 5.3.2 with the following plugins:

  • WP GraphQL 0.7.0
  • WP GraphQL Polylang 0.3.8
  • Polylang 2.6.10

Does not work when called from PHP using `do_graphql_request()`

See wp-graphql/wp-graphql#1021 (comment)

Actually wp-graphql-polylang cannot work at all when called from PHP. That's because Polylang initializes itself into a specific mode which maybe be "admin", "frontend" or "rest" and now via wp-graphql-polylang "graphl" too. Once the intialization has been done it cannot changed anymore (at least to my knowledge).

So in wp-graphql-polylang I must tell it to go to the graphql mode as soon as possible. If it is too late Polylang will initialize into the frontend mode. This does happen before the init. The frontend mode would filter everything by the default language which is no good for a graphql api because you'll want to specify the language using the where-args so you can query posts in multiple languages if you want.

Getting the author bio in the proper language

Here's the GraphQL query:

query Blog {
  post(id: "my-post-slug-in-spanish", idType: SLUG) {
    slug
    excerpt
    date
    author {
      node {
        description
      }
    }
  }
}

The author description is displayed in English, instead of Spanish.

While on the user settings, we have set the proper translations for the author description:
CleanShot 2023-08-18 at 09 56 02@2x

Am I missing something?

Previous and next post by language

I use previous next post wpgraphql plugin from this repo:
https://github.com/m-inan/wp-graphql-next-previous-post

It gets next post basically;

register_graphql_field('Post', 'next', [
            'type' => 'Post',
            'description' => __(
                'Next post'
            ),
            'resolve' => function (Post $post, array $args, AppContext $context) {
                global $post;

                // get post
                $post = get_post($post->ID, OBJECT);

                // setup global $post variable
                setup_postdata($post);

                $next = get_next_post();

                wp_reset_postdata();

                if (!$next) {
                    return null;
                }

                return DataSource::resolve_post_object($next->ID, $context);
            },
        ]);

I'm not a php guy. I searched some polylang functions and tried but not succeded. How can I add polylang feature to this code?

Thanks.

Retrieving category translation generating error

Hello, im trying to retrieve translations on category and it's giving me the following internal error, there are no PHP error log for this error to debug further. There exists a valid translated category im passing the ID for.

Graphql:
query MyQuery { category(idType: DATABASE_ID, id: 2) { name translations { id } } }

Error:{ "errors": [ { "message": "Internal server error", "category": "internal", "locations": [ { "line": 5, "column": 7 } ], "path": [ "category", "translations", 0, "id" ] } ], "data": { "category": { "name": "xyz", "translations": [ null ] } } }

Cannot query viewer when logged in other source than the cms

Hi!
I have an encountered an issue when I was trying to fetch the currently logged in user through the viewer query.
I have Polylang v2.8.4, WP GraphQL Polylang v0.5.0 enabled. My authentication plugin is WPGraphQL JWT Authentication v0.4.1.

Steps to reproduce:

  1. Log in through mutation query. Get back jwt token. No issue here at all.
  2. Pass jwt token as Bearer in authentication header for the viewer query. The query looks like this:
query getViewerCollections {
    viewer {
         name
         email
     }
}

The server response is 403 forbidden and:

{
    "data": {
        "viewer": null
    }
}

When I disable the WP GraphQL Polylang plugin then everything works as intended.

Any ideas on why this might happen?

How to get actual language for product [polylang/woocomerce]

Hi
I have a problem with a get a real language for products.
How can you download the current language of the product or is it possible?.Thanks for the help in advance
"data": { "products": { "nodes": [ { "language": { "code": "PL" }, "name": "test", "slug": "91" }, { "language": { "code": "PL" <---- here it should be EN }, "name": "English prod", "slug": "test-prod" },

The plugin does not show "language" for WooCommerce products

I am using wp-graphql-polylang and wp-graphql-woocommerce, but when querying products I cannot find the "language" schema. I now used a work around through an ACF select field, but it would be nice to have languages available for WooCommerce products 👍

Querying for translations on categories causes Internal server error

As the title says, querying translations in categories causes an internal server error.

Query:

{
  categories {
    nodes {
      translations {
        id
      }
    }
  }
}

Response:

{
  "errors": [
    {
      "message": "Internal server error",
      "category": "internal",
      "locations": [
        {
          "line": 5,
          "column": 9
        }
      ],
      "path": [
        "categories",
        "nodes",
        0,
        "translations",
        0,
        "id"
      ]
    },
    {
      "message": "Internal server error",
      "category": "internal",
      "locations": [
        {
          "line": 5,
          "column": 9
        }
      ],
      "path": [
        "categories",
        "nodes",
        1,
        "translations",
        0,
        "id"
      ]
    }
  ],
  "data": {
    "categories": {
      "nodes": [
        {
          "translations": [
            null
          ]
        },
        {
          "translations": [
            null
          ]
        }
      ]
    }
  }
}

Get queried/resolved language for a given post

I am trying to register a GraphQL field (https://www.wpgraphql.com/2020/03/11/registering-graphql-fields-with-arguments/), and inside the resolve callback, I need to do a WP query, and for that I’d like to query posts in specific language. How can I get the current language? Unfortunately pll_current_language() returns false.

You specifically say that you have deactivated the "native" way Polylang fetches posts when using WP_Query, but actually, in my case I'd prefer if it only queried in the language that was resolved.

I query by URI like this:

query Posts {
  post(id: "/en/unlimited", idType: URI) {

Although not very pretty, I came up with this workaround that gives me the language of the queried object:

/**
 * For lack of a better way to get the currently queried language inside GraphQL
 * @return mixed
 */
function get_queried_language() {
    $lang = pll_get_post_language($GLOBALS['wp_the_query']->queried_object->ID);
    return ($lang) ? $lang : pll_default_language();
}

A better solution would be if pll_current_language could be used inside resolve of register_graphql_field

Get single page by language

I believe this repository is missing the ability to specifiy language when fetching a single page/post. E.g.:

query Pages {
  page(id: "some-slug", idType: URI, language: EN) {

Internal server error when querying an author using nodeByUri

I am trying to do a seedQuery as described here: https://faustjs.org/reference/seed-query
When I do this for a author URL with the format: blog/author/ I get a server error when the wp-graphql-polylang plugin is activated.

Steps to reproduce:

  1. Set permalink structure to: /blog/%postname%/
  2. Activate the Polylang plugin and the WPGraphQL plugin.
  3. Do the following query from within the WPGraphiQL IDE in WordPress Admin(this was simplified a lot - but enough to trigger the error):
query GET_NODE_BY_URI( $uri: String! = "") {
  ... on RootQuery {
    node: nodeByUri(uri: $uri) {
      uri
      id
    }
  }
}

Variables:
{ "uri": "blog/author/<author-name>" }

This will return the following data:

  "data": {
    "node": {
      "uri": "/blog/author/ejaasheadless/",
      "id": "dXNlcjox"
    }
  }
  1. Activate the WP GraphQL Polylang plugin and execute the query from within the WPGraphiQL IDE again. This will return the following error:
"debugMessage": "WPGraphQL\\Registry\\TypeRegistry::get_type(): Argument #1 ($type_name) must be of type string, null given, called in /var/www/html/wp-content/plugins/wp-graphql/src/Type/InterfaceType/UniformResourceIdentifiable.php on line 59",
     "message": "Internal server error",

I have tested on:

  • WordPress v. 6.3.2
  • WPGraphQL v. 1.17.0
  • Polylang v. 3.5.1
  • WP GraphQL Polylang v. 0.6.0

Menu-Language not working

Hi there,
First of all, wp-graphql-polylang is awesome!

I found an issue when using it with WPGraphql Version 0.12.3 where menu-languages are not working anymore.

I figured out, that the filter graphql_menu_item_connection_args you're using has been removed and is not applied anymore.

Maybe there is another way, but I couldn't find one.

Thanks in advance,
David

Add `language` where arg to `menus`

So we could do this

{
  menus(where: {location: FOOTER, language: EN}) {
    nodes {
      slug
      name
    }
  }
}

Note! If you want to get menu items in a specific language for a given location you can use menuItems which is used most of the time used when building menus for the frontend.

{
  menuItems(where: {location: FOOTER, language: EN}) {
    nodes {
      label
      url
    }
  }
}

Language field do not exist in ACF options

Hi, I am trying to get access to the "language" field while querying ACF option fields but I am not able to do so - there is no such field and as a result, there is no way to do a query like this:

siteSettings(language: EN) {
    siteSettings {
        footerTitle
    }
}

I have the plugin installed in WordPress, along with ACF Options for Polylang, Advanced Custom Fields PRO, WP Gatsby, WP GraphQL, WP GraphQL Polylang, WPGraphQL Custom Post Type UI, WPGraphQL for Advanced Custom Fields - uninstalling singular and checking if the problem disappears does not work and that's the reason I am asking here.

From the Gatsby side, I was using both gatsby-source-wordpress and gatsby-source-graphql, and no one is showing anything like "languages" filter.

Thank you in advance for any help!

When you query for a single post via URI, then the language is ignored

When you query for a single post via URI, then the language parameter in the URL is ignored.
Query returns only the post in the standard language:

query MyQuery {
  teamMember(id: "/fr/team_members/lorem-ipsum/", idType: URI) {
    slug
    language {
      code
    }
    uri
  }
}

It should return the the French version for the query above.

Argument 1 passed to WPGraphQL\\Extensions\\Polylang\\PostObject::WPGraphQL\\Extensions\\Polylang\\{closure}() must be an instance of WPGraphQL\\Model\\Post, instance of WPGraphQL\\Model\\PostType given

I am getting this error, not sure if it is related:

Argument 1 passed to WPGraphQL\\Extensions\\Polylang\\PostObject::WPGraphQL\\Extensions\\Polylang\\{closure}() must be an instance of WPGraphQL\\Model\\Post, instance of WPGraphQL\\Model\\PostType given, called in /Users/mf/Projects/myproject/wp-content/plugins/wp-graphql/src/Utils/InstrumentSchema.php on line 151

Happened after adding:

translations {
	link
	language {
		locale
	}
}

To my page query.

Does nodeByUri + graphql-polylang support getting the frontpage in several languages?

@esamattis terve from Estonia!

I was wondering if nodeByUri + graphql-polylang should be able to retrieve the frontpage for each language if only given a language slug such as /fi or /de ?

I'm currently using PolyLang and PolyLang GraphQL but I'm only able to retrieve the default language and the frontpages in other languages result in null.)

I first asked the wp-graphql team (wp-graphql/wp-graphql#2249) but they are no sure either so probably it's more appropriate to ask here.

Thanks
Kris

where filter doesn't work on page {}

I'm trying to get a page by URI and language but it's ignoring the /es/ and I only get the english content.

Instead of getting the Spanish content using translation { ... } node, Is there any way to filter the page and get only spanish?

Like this: page(id: "/es/page", idType: URI, where: {language: ES}) { ... }

Screen Shot 2021-08-05 at 14 11 07

Query string translations

Hello,

is it possible to query string translations via GraphQL with that plugin?
I didn't find a solution yet...

Expose all translations strings

This could work

function get_polylang_strings($slug = 'en') {
	$values 		= [];
    $term           = get_term_by( 'slug' , $slug , 'language' ); 
    $posts          = get_posts(array( 'name' => 'polylang_mo_'.$term->term_id , 'post_type' => 'polylang_mo' , 'post_status' => 'private' , 'posts_per_page' =>1 ));
    $post_id        = $posts[0]->ID;
    $translations   = get_post_meta( $post_id , '_pll_strings_translations' , true );
    if(!$translations) {
    	return;
    }
    foreach($translations as $translation) {
    	$values[$translation[0]] = $translation[1];
    }
    return $values;
}

See

https://wp-graphql.slack.com/archives/CH3E1FZHB/p1580230496018300

Save Posts to local json file (Field \"language\" is not defined by type RootQueryToEventConnectionWhereArgs.)

I'm trying to save my custom post type posts to local json file but the problem is when i save it with the language attribute a received the error.

{"errors":[{"message":"Field "language" is not defined by type RootQueryToEventConnectionWhereArgs.","extensions":{"category":"graphql"},"locations":[{"line":2,"column":44}]}]}

Maybe you help me to fix my code or maybe you can suggest solution to save posts to local json file.

Also in debug when file trying to save post there is one more error

Deprecated: Function WPGraphQL\Data\Connection\AbstractConnectionResolver::getArgs is deprecated since version 1.11.0! Use WPGraphQL\Data\Connection\PostObjectConnectionResolver::get_args() instead. in /home/localhost.com/public_html/wp-includes/functions.php on line 5383

add_action( 'graphql_register_types', function() { register_graphql_enum_type( 'LanguageCodeFilterEnum', [ 'description' => __( 'Filter by language code', 'domain' ), 'values' => [ 'ALL' => [ 'value' => 'all', 'description' => __( 'All languages', 'domain' ), ], 'CURRENT' => [ 'value' => 'current', 'description' => __( 'Current language', 'domain' ), ], 'EN' => [ 'value' => 'EN', 'description' => __( 'EN language', 'domain' ), ], 'UK' => [ 'value' => 'UK', 'description' => __( 'UK language', 'domain' ), ], ], ] ); } );

`function save_event_data_to_json($post_id) {
$post_type = get_post_type($post_id);
if ($post_type !== 'event') {
return;
}

$query_en = <<<GRAPHQL
query HOME_PAGE($language: LanguageCodeFilterEnum = EN){
events(first: 1000, after: null, where: {language: $language}) {
edges {
node {
title
uri
slug
eventId
featuredImage {
node {
sourceUrl
}
}
eventPost {
previewSection {
dateEnd
dateStart
eventTitle
imgSource
interfaceDate
}
}
eventPeriods {
nodes {
id
name
eventPeriodsTime {
dateEnd
dateStart
}
}
}
eventTypes {
nodes {
id
name
}
}
}
}
}
}
GRAPHQL;

$data_en = graphql(array(
'query' => $query_en,
));

$file_en = ABSPATH . 'wp-content/uploads/events_en.json';
if (WP_Filesystem()) {
global $wp_filesystem;
$wp_filesystem->put_contents($file_en, json_encode($data_en, JSON_UNESCAPED_UNICODE), FS_CHMOD_FILE);
}
}
add_action('save_post', 'save_event_data_to_json');
add_action('edit_post', 'save_event_data_to_json');`

backend crashes on deactivating plugin

We're running a WordPress multisite installation and when the 'WP GraphQL' plugin is deactivated, it crashes the backend and generates the following log

[Thu Jan 02 13:22:40.765263 2020] [php7:notice] [pid 3656] [client 172.31.15.44:50646] PHP Fatal error: Uncaught Error: Class ‘WPGraphQL\Router’ not found in /var/www/html/xyz/wp-content/plugins/wp-graphql-polylang-0.3.5/src/Loader.php:110\nStack trace:\n#0 /var/www/html/xyz/wp-content/plugins/wp-graphql-polylang-0.3.5/src/Loader.php(47): WPGraphQL\Extensions\Polylang\Loader->is_graphql_request()\n#1 /var/www/html/xyz/wp-includes/class-wp-hook.php(288): WPGraphQL\Extensions\Polylang\Loader->get_pll_model(‘PLL_Model’)\n#2 /var/www/html/xyz/wp-includes/plugin.php(206): WP_Hook->apply_filters(‘PLL_Model’, Array)\n#3 /var/www/html/xyz/wp-content/plugins/polylang/include/class-polylang.php(222): apply_filters(‘pll_model’, ‘PLL_Model’)\n#4 /var/www/html/xyz/wp-includes/class-wp-hook.php(288): Polylang->init(‘’)\n#5 /var/www/html/xyz/wp-includes/class-wp-hook.php(312): WP_Hook->apply_filters(NULL, Array)\n#6 /var/www/html/xyz/wp-includes/plugin.php(478): WP_Hook->do_action(Array)\n#7 /var/www/html/xyz/wp-settings.php(392): do_action(’plugins_loade in /var/www/html/xyz/wp-content/plugins/wp-graphql-polylang-0.3.5/src/Loader.php on line 110, referer: https://www.xyz.com/xyz/wp-admin/edit.php?s=indian&post_status=all&post_type=post&action=-1&m=0&cat=0&seo_filter&readability_filter&paged=1&action2=-1

nodeByURI not returning correct node when translations have same slug

Hi,

First: thanks for the plugin which is great! 👏

My setup:

  • WP 5.8.3
  • Polylang Pro 3.1.2 (the pro version gives the possibility to share the same slug between translations)
  • WPGraphql 1.6.12
  • WPGraphql Polylang 0.6.0
  • Active theme: TwentyTwentyOne 1.4.0
  • Three languages set: FR*, EN & DE (FR is the default)

When I have posts or pages sharing the same slug between translations, the RootQuery nodeByUri field does not return the correct node according to the localized URI.

As you can see the queries in the GraphQLi (screenshot below), the three queries return the same node which can be any of the translated node.

Capture d’écran 2022-01-21 à 17 49 38 Capture d’écran 2022-01-21 à 17 49 59

I could find a workaround to make it work, but it feels really dirty:

// Add lang arg to $extra_query_vars to nodeByURI rootquery
add_filter( 'graphql_RootQuery_fields',  function ($fields) {
	if ( isset($fields['nodeByUri']) ) {
		$fields['nodeByUri']['resolve'] = function ( $root, $args, AppContext $context ) {
			if ( empty( $args['uri'] ) ) return null;

			$extra_query_vars = [];
			$parsed_url = wp_parse_url( $args['uri'] );

			// If we match a language in the URI
			if ( preg_match("/^\/?(\w{2})\/.+/", $parsed_url['path'], $matches) ) {
				$extra_query_vars['lang'] = $matches[1];
				$extra_query_vars['is_graphql_nodebyuri'] = true;
			}

			return $context->node_resolver->resolve_uri( $args['uri'], $extra_query_vars );
		};
	}
	return $fields;
}, 20);

// rewrite SQL query to include lang for pages & posts
add_filter( 'query', function query_pagename_nodebyuri( $query ) {
	global $wp;

	if ( isset($wp->query_vars['is_graphql_nodebyuri']) && isset($wp->query_vars['lang']) ) {
		global $wpdb;
		if ( isset($wp->query_vars['pagename']) ) {
			$pagename_in = implode("','", explode('/', $wp->query_vars['pagename']));
			if ( preg_match("/post_name IN \('$pagename_in'\)/", $query) ) {
				$query = "
					SELECT p.ID, p.post_name, p.post_parent, p.post_type
					FROM {$wpdb->posts} AS p
						LEFT JOIN {$wpdb->term_relationships} AS tr ON p.ID=tr.object_id
						LEFT JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id=tt.term_taxonomy_id
						LEFT JOIN {$wpdb->terms} AS t ON tt.term_id=t.term_id
					WHERE
						p.post_name IN ('$pagename_in')
						AND p.post_type IN ('post','page','attachment')
						AND tt.taxonomy='language'
						AND t.slug='{$wp->query_vars['lang']}'
				";
			}
		}
		else if ( isset($wp->query_vars['name']) && preg_match("/post_name IN \('{$wp->query_vars['name']}'\)/", $query) ) {
			$query = "
				SELECT p.ID, p.post_name, p.post_parent, p.post_type
				FROM {$wpdb->posts} AS p
					LEFT JOIN {$wpdb->term_relationships} AS tr ON p.ID=tr.object_id
					LEFT JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id=tt.term_taxonomy_id
					LEFT JOIN {$wpdb->terms} AS t ON tt.term_id=t.term_id
				WHERE
					p.post_name IN ('{$wp->query_vars['name']}')
					AND post_type IN ('post','attachment')
					AND tt.taxonomy='language'
					AND t.slug='{$wp->query_vars['lang']}'
			";
		}
} );

However, this is really risky business as I'm changing the SQL query to the DB to handle the language. So I'm wondering if there is a better solution to fix this translation issues with nodeByUri ??

Retrieving trashed post translation causing error

Hello, im trying to retrieve translations on post with uri which does not have a translation and it's giving me the following internal server error

post(id: "xyz", idType: URI) {
      id
      language {
        locale
      }
      translations {
        link
        language {
          locale
        }
        uri
      }
    }

when i remove uri from the graphql, the query returns fine. If theres a translation against the post, the query works fine.

"errors": [
    {
      "message": "Internal server error",
      "path": [
        "wpgraphqlbuildings",
        "post",
        "translations",
        0,
        "uri"
      ],

"Found a duplicate ID in WordPress"

Description

We have a GatsbyJS site using gatsby-source-wordpress.

When launching gatsby develop, I get the error message : "Found a duplicate ID in WordPress - this means you will have fewer nodes in Gatsby than in WordPress. This will need to be resolved in WP by identifying and fixing the underlying bug with your WP plugins or custom code."

The problem goes away if I disable WP GraphQL Polylang ; of course then my Gatsby translation modules break.

Steps to reproduce

Expected result

The develop should launch properly.

Actual result

Get the error message mentioned above, and the dev server breaks.

Environment

System:
    OS: Windows 10 10.0.17763
    CPU: (8) x64 Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz
  Binaries:
    Node: 12.18.3 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.17.3 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 6.14.6 - C:\Program Files\nodejs\npm.CMD
  Languages:
    Python: 3.8.5
  Browsers:
    Chrome: 89.0.4389.90
    Edge: Spartan (44.17763.831.0)
  npmPackages:
    gatsby: ^3.1.1 => 3.1.1
    gatsby-image: ^2.10.0 => 2.11.0
    gatsby-plugin-alias-imports: ^1.0.5 => 1.0.5
    gatsby-plugin-catch-links: ^3.1.0 => 3.1.0
    gatsby-plugin-feed: ^3.1.0 => 3.1.0
    gatsby-plugin-gatsby-cloud: ^2.1.0 => 2.1.0
    gatsby-plugin-google-tagmanager: ^3.1.0 => 3.1.0
    gatsby-plugin-manifest: ^3.1.0 => 3.1.0
    gatsby-plugin-meta-redirect: ^1.1.1 => 1.1.1
    gatsby-plugin-offline: ^4.1.0 => 4.1.0
    gatsby-plugin-react-helmet: ^4.1.0 => 4.1.0
    gatsby-plugin-remove-serviceworker: ^1.0.0 => 1.0.0
    gatsby-plugin-sharp: ^2.13.1 => 2.14.3
    gatsby-plugin-sitemap: ^3.1.0 => 3.1.0
    gatsby-plugin-split-css: ^2.0.0 => 2.0.0
    gatsby-plugin-webpack-bundle-analyser-v2: ^1.1.10 => 1.1.21
    gatsby-remark-images: ^4.1.0 => 4.1.0
    gatsby-source-filesystem: ^3.1.0 => 3.1.0
    gatsby-source-wordpress: ^5.1.0 => 5.1.0
    gatsby-source-youtube-v3: ^3.0.0 => 3.0.0
    gatsby-transformer-remark: ^3.1.0 => 3.1.0
    gatsby-transformer-sharp: ^3.1.0 => 3.1.0
  npmGlobalPackages:
    gatsby-cli: 3.1.0

Our WP Plugins are :

Advanced Custom Fields, Version 5.9.5
Co-Authors Plus, Version 3.4.3
Genesis Custom Blocks, Version 1.1.0
More Fields, Version 2.1
Polylang, Version 3.0.3
WordPress Importer, Version 0.7
WP Gatsby, Version 1.0.6
WP GraphQL, Version 1.3.2
WP GraphQL Polylang, Version 0.5.0
WP REST - Polylang, Version 1.0.0
Yoast SEO Premium, Version 7.5.2

What has been tried so far

  • Updating all my plugins, both in Gatsby and in WP.
  • Contacting our WP host : there's no actual duplicate IDs in the database. Plus, the problem disappears if I disable the WP GraphQL Polylang plugin, so this seems to be closer to the root cause.
  • The problem seems to lie specifically with the MediaItem ID #35306 ; which, I believe, is just the feature image for the first post that's detected that has a translation.
  • Lower GATSBY_CONCURRENT_DOWNLOAD ; it's set to 1 and still doesn't help.
  • Tinker with the gatsby-source-wordpress plugin : the error message comes from the file /dist/steps/source-nodes/fetch-nodes/fetch-nodes-paginated.js, line 117. I was able to get the dev server to run once by commenting out the whole line 117. Haven't been able to do it twice though. Playing with that file is also how I isolated the MediaItem #35306 as being problematic (by console-logging the node.databaseId.)

EDIT : Added some details.

IsFrontPage and isPostsPage

Hi,

While working on a recent project I realised that both this fields don't return the values I would expect for translated posts.
I've ended up overriding the original resolvers to achieve this.
Let me know if you see fit and I'd be happy to open a PR.

add_filter( 'graphql_Page_fields', function( $fields ) {
  if ( isset( $fields['isFrontPage'] ) ) {
    $fields['isFrontPage']['resolve'] = function(\WPGraphQL\Model\Post $post) {
      if ( 'page' !== $post->post_type || 'page' !== get_option( 'show_on_front' ) ) {
        return false;
      }

      $post_translations = array_values(pll_get_post_translations($post->ID));
      $front_page_id     = absint( get_option( 'page_on_front', 0 ) );

      return in_array($front_page_id, $post_translations);
    };
  }

  if ( isset( $fields['isPostsPage'] ) ) {
    $fields['isPostsPage']['resolve'] = function(\WPGraphQL\Model\Post $post) {
      if ( 'page' !== $post->post_type ) {
        return false;
      }

      $post_translations = array_values(pll_get_post_translations($post->ID));
      $page_for_posts_id = absint( get_option( 'page_for_posts', 0 ) );

      return 'posts' !== get_option( 'show_on_front', 'posts' ) && in_array($page_for_posts_id, $post_translations) === true;
    };
  }
  return $fields;
}, 10, 1 );

Unable to find Language in where clause

Hi all,
I have installed all the plugin,
Acf Pro,
Polylang 3.1.2
graphql for polylang
acf for graphql

language is not there when looking into the where clause am i doing something wrong?

Add docs to README for running tests locally

In trying to help fix an issue I attempted to install the plugin and run tests locally.

I got close, but missed some detail and was unable to run the tests locally to help debug an issue.

It would be good to have a step-by-step outline in the README of how to get tests running locally.

Thanks!

add_post_type_fields for language is not working for woocomerce products

I am trying to access the translations of products and the current language but its not working. I searched for the get_allowed_post_types and I think there is a timing error so the product post type is not fetched. I don't know if this is a wp-graphql-polylang problem or a wp-graphql-woocomerce but I had to call again the add_post_type_fields in my function theme to make the language and the translation work for them.

return multiple times the same post ??

Hi , It return multiple times same post with same data , two languages ( EN & ES )
when i query a english version it returns two times of english version
Query posts { nodes { translation(language: EN) { title(format: RENDERED) } } }
Output
"data": { "posts": { "nodes": [ { "translation": { "title": "Hello World" } }, { "translation": { "title": "Hello World" } } ] } },

with Spanish Version
"data": { "posts": { "nodes": [ { "translation": { "title": "Hola Mundo" } }, { "translation": { "title": "Hola Mundo" } } ] } },

Wrong translations when changing primary language

Hi!

We've been using this plugin for some time now in combination with

  • wp-graphql
  • polylang

And when we try to change the primary language on polylang, the plugin still thinks the primary language is the old one. The default language returned by the query is right, but when querying pages or custom post types, their translated URIs are not quite right.

image

For example here, our main language is spanish, so the main website url should not have a /es at the end of the url but the other languages should. In the picture we can clearly see that the plugin still thinks the main language is english.

Do you have tips or way to resolve this issue ? Thanks.

Issue with WP GraphQL Polylang plugin when querying menus

I am using Polylang Version 3.3.1 and WP GraphQL Polylang Version 0.6.0 plugins on my WordPress website. While querying menus using the following code:

{
menus {
nodes {
slug
menuItems {
nodes {
uri
}
}
}
}
}

I encountered an error and no results were displayed. Upon investigating, I found that the issue is caused by an deprecated function in the MenuItem.php. The function "getArgs()" needs to be updated to "get_args()" to fix the issue.

Please update the WP GraphQL Polylang plugin to fix this issue. Thank you.

$args = $resolver->getArgs();

Language prefixes do not work in `idType: URI` queries

Hey,

I think at the current time it is literally impossible to fetch home page of non default language. Everything works fine for pages. Take look at full report listed below.

Fetching default home page

query Page {
  pageBy(uri: "/") {
    title
  }
  page(id: "/", idType: URI) {
    title
  }
}
  • Fetching using pageBy - works as expected
  • Fetching using page - works as expected

Fetching home page for selected language

Disclaimer: Expected page exists, uses directory based permalinks and is available through WordPress through URL like: wordpress-instance.com/pl

query Page {
  pageBy(uri: "/pl") {
    title
  }
  page(id: "/pl", idType: URI) {
    title
  }
}
  • Fetching using pageBy - not working at all
  • Fetching using page - not working at all

Fetching normal page for selected language

query Page {
  pageBy(uri: "/pl/kontakt") {
    title
  }
  page(id: "/pl/kontakt", idType: URI) {
    title
  }
}
  • Fetching using pageBy - works as expected
  • Fetching using page - works as expected

Fetching normal page for selected language without language prefix

query Page {
  pageBy(uri: "/kontakt") {
    title
  }
  page(id: "/kontakt", idType: URI) {
    title
  }
}
  • Fetching using pageBy - works unexpected, as Page's permalink is /pl/kontakt not /kontakt
  • Fetching using page - works unexpected, as Page's permalink is /pl/kontakt not /kontakt

Unless I am doing something wrong, I think there could be a great benefit by exposing additional language parameter under pageBy entity, alongside already existing id, pageId, and uri so that individual page could be safely retrieved in expected language. This should also fix fetching home page for different language issue at the same time.

What do you think?

PS. Excellent package by the way!

Querying ACF/Option fields via GraphQL - Set language?

Hi,

It's more like a question but an issue.

We're using Polylang in combination with WPGraphQL Plugin and also ACF.
When we're trying to query specific ACF Options field values via custom endpoints, we don't receive anything but NULL.

Is there any chance to set the language and get the correct data from option fields while resolving our request?
I tried to set the language with some class functions delivered within the plugin.

PLL()->curlang = PLL()->model->get_language($args['language']);
echo pll_current_language();  // Returns the language set by the line above

Sadly this line doesn't work, it seems that the language isn't really set inside the context.

Menu filters not working with wordpress-source-experimental plugin

Hello, thank you for this awesome plugin.

I just figured out that I can filter menu items by language when using the WPGraphiql plugin IDE:
Screenshot 2021-02-05 at 19 17 52

Unfortunately the same filter seems to be unavailable using the gatsby-source-wordpress-experimental plugin. The language filter works for all the other types, such as posts, pages etc:

Screenshot 2021-02-05 at 19 19 09

Is there any reason why the wordpress-source-experimental plugin isn't recognizing this filter?

Thank you in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.