|
1 | 1 | <?php |
2 | 2 |
|
| 3 | +use GraphQL\Type\Definition\ResolveInfo; |
3 | 4 | use WPGraphQL\Registry\TypeRegistry; |
4 | 5 |
|
5 | 6 | use WPGraphQL\Acf\Admin\PostTypeRegistration; |
@@ -40,6 +41,11 @@ public function init(): void { |
40 | 41 |
|
41 | 42 | add_filter( 'graphql_data_loaders', [ $this, 'register_loaders' ], 10, 2 ); |
42 | 43 | add_filter( 'graphql_resolve_node_type', [ $this, 'resolve_acf_options_page_node' ], 10, 2 ); |
| 44 | + /** |
| 45 | + * This filters any field that returns the `ContentTemplate` type |
| 46 | + * to pass the source node down to the template for added context |
| 47 | + */ |
| 48 | + add_filter( 'graphql_resolve_field', [ $this, 'page_template_resolver' ], 10, 9 ); |
43 | 49 |
|
44 | 50 | do_action( 'wpgraphql/acf/init' ); |
45 | 51 | } |
@@ -211,4 +217,32 @@ public function show_graphql_debug_messages(): void { |
211 | 217 | } |
212 | 218 | } |
213 | 219 |
|
| 220 | + /** |
| 221 | + * Add the $source node as the "node" passed to the resolver so ACF Fields assigned to Templates can resolve |
| 222 | + * using the $source node as the object to get meta from. |
| 223 | + * |
| 224 | + * @param mixed $result The result of the field resolution |
| 225 | + * @param mixed $source The source passed down the Resolve Tree |
| 226 | + * @param array $args The args for the field |
| 227 | + * @param \WPGraphQL\AppContext $context The AppContext passed down the ResolveTree |
| 228 | + * @param \GraphQL\Type\Definition\ResolveInfo $info The ResolveInfo passed down the ResolveTree |
| 229 | + * @param string $type_name The name of the type the fields belong to |
| 230 | + * @param string $field_key The name of the field |
| 231 | + * @param \GraphQL\Type\Definition\FieldDefinition $field The Field Definition for the resolving field |
| 232 | + * @param mixed $field_resolver The default field resolver |
| 233 | + * |
| 234 | + * @return mixed |
| 235 | + */ |
| 236 | + public function page_template_resolver( $result, $source, $args, \WPGraphQL\AppContext $context, ResolveInfo $info, string $type_name, string $field_key, \GraphQL\Type\Definition\FieldDefinition $field, $field_resolver ) { |
| 237 | + if ( strtolower( 'ContentTemplate' ) !== strtolower( $info->returnType ) ) { |
| 238 | + return $result; |
| 239 | + } |
| 240 | + |
| 241 | + if ( is_array( $result ) && ! isset( $result['node'] ) && ! empty( $source ) ) { |
| 242 | + $result['node'] = $source; |
| 243 | + } |
| 244 | + |
| 245 | + return $result; |
| 246 | + } |
| 247 | + |
214 | 248 | } |
0 commit comments