Skip to content

Commit 29739a3

Browse files
committed
- Add filter to graphql_resolve_field to pass the Node down to the template resolver so ACF can properly resolve fields on the template object using the passed down "node" as the object to resolve fields from.
1 parent aa86350 commit 29739a3

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/WPGraphQLAcf.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?php
22

3+
use GraphQL\Type\Definition\ResolveInfo;
34
use WPGraphQL\Registry\TypeRegistry;
45

56
use WPGraphQL\Acf\Admin\PostTypeRegistration;
@@ -40,6 +41,11 @@ public function init(): void {
4041

4142
add_filter( 'graphql_data_loaders', [ $this, 'register_loaders' ], 10, 2 );
4243
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 );
4349

4450
do_action( 'wpgraphql/acf/init' );
4551
}
@@ -211,4 +217,32 @@ public function show_graphql_debug_messages(): void {
211217
}
212218
}
213219

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+
214248
}

0 commit comments

Comments
 (0)