diff --git a/src/PostObject.php b/src/PostObject.php index b3345b2..3c58b45 100644 --- a/src/PostObject.php +++ b/src/PostObject.php @@ -225,7 +225,19 @@ function add_post_type_fields(\WP_Post_Type $post_type_object) continue; } - $posts[] = new \WPGraphQL\Model\Post($translation); + $model = new \WPGraphQL\Model\Post($translation); + + // If we do not filter out privates here wp-graphql will + // crash with 'Cannot return null for non-nullable field + // Post.id.'. This might be a wp-graphql bug. + // Interestingly only fetching the id of the translated + // post caused the crash. For example title is ok even + // without this check + if ($model->is_private()) { + continue; + } + + $posts[] = $model; } return $posts; diff --git a/tests/wpunit/PostObjectQueryTest.php b/tests/wpunit/PostObjectQueryTest.php index 4861b2a..b0166ca 100644 --- a/tests/wpunit/PostObjectQueryTest.php +++ b/tests/wpunit/PostObjectQueryTest.php @@ -170,6 +170,52 @@ public function testCanFetchTranslatedVersions() $this->assertEquals($expected, $data['data']['postBy']); } + public function testDraftTranslationDoesNotCrash() + { + $fi_post_id = wp_insert_post([ + 'post_title' => 'Finnish post version', + 'post_content' => '', + 'post_type' => 'post', + 'post_status' => 'publish', + ]); + pll_set_post_language($fi_post_id, 'fi'); + + $en_post_id = wp_insert_post([ + 'post_title' => 'English post version', + 'post_content' => '', + 'post_type' => 'post', + 'post_status' => 'draft', + ]); + pll_set_post_language($en_post_id, 'en'); + + pll_save_post_translations([ + 'en' => $en_post_id, + 'fi' => $fi_post_id, + ]); + + $query = " + query Post { + postBy(postId: $fi_post_id) { + title + translations { + title + id + } + } + } + "; + + $data = do_graphql_request($query); + $this->assertArrayNotHasKey('errors', $data, print_r($data, true)); + + $expected = [ + 'title' => 'Finnish post version', + 'translations' => [], + ]; + + $this->assertEquals($expected, $data['data']['postBy']); + } + public function testCanFetchSingleTranslatedVersion() { $fi_post_id = wp_insert_post([