Created
October 8, 2022 08:58
-
-
Save marek-miotelka/f4e90c12ce62f7fbe023814d10591f81 to your computer and use it in GitHub Desktop.
Support for Gravity Forms ACF Field in WPGraphQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| if (!defined('ABSPATH')) { | |
| exit; | |
| } | |
| add_filter('wpgraphql_acf_supported_fields', function ($supported_fields) { | |
| $supported_fields[] = 'forms'; | |
| return $supported_fields; | |
| }); | |
| add_filter('wpgraphql_acf_register_graphql_field', function ($field_config, $type_name, $field_name, $config) { | |
| $acf_field = $config['acf_field'] ?? null; | |
| $acf_type = $acf_field['type'] ?? null; | |
| // ignore all other field types | |
| if (!$acf_field || $acf_type !== 'forms') { | |
| return $field_config; | |
| } | |
| if ($acf_field['return_format'] === 'post_object' && is_plugin_active('wp-graphql-gravity-forms/wp-graphql-gravity-forms.php')) { | |
| if (empty($acf_field['multiple'])) { | |
| $field_config['type'] = \WPGraphQL\GF\Type\WPObject\Form\Form::$type; | |
| $field_config['resolve'] = function ($root, $args, \WPGraphQL\AppContext $context) use ($acf_field, $config) { | |
| $form = null; | |
| $form_id = get_field( $config['acf_field']['key'], $root->databaseId ); | |
| if ($form_id) { | |
| $form = $context->get_loader(\WPGraphQL\GF\Data\Loader\FormsLoader::$name)->load_deferred($form_id); | |
| } | |
| return $form ?? null; | |
| }; | |
| } else { | |
| $field_config['type'] = ['list_of' => \WPGraphQL\GF\Type\WPObject\Form\Form::$type]; | |
| $field_config['resolve'] = function ($root, $args, \WPGraphQL\AppContext $context) use ($acf_field, $config) { | |
| $forms = []; | |
| $form_ids = get_field( $config['acf_field']['key'], $root->databaseId ); | |
| if (!empty($form_ids) && is_array($form_ids)) { | |
| foreach ($form_ids as $form_id) { | |
| if ($form_id) { | |
| $form = $context->get_loader(\WPGraphQL\GF\Data\Loader\FormsLoader::$name)->load_deferred($form_id); | |
| $forms[] = $form; | |
| } | |
| } | |
| } | |
| return !empty($forms) ? $forms : []; | |
| }; | |
| } | |
| // Form id | |
| } else { | |
| if (empty($acf_field['multiple'])) { | |
| $field_config['type'] = 'Integer'; | |
| } else { | |
| $field_config['type'] = ['list_of' => 'Integer']; | |
| $field_config['resolve'] = function ($root, $args) use ($acf_field, $config) { | |
| $value = get_field( $config['acf_field']['key'], $root->databaseId ); | |
| return !empty($value) && is_array($value) ? $value : []; | |
| }; | |
| } | |
| } | |
| return $field_config; | |
| }, 10, 4); |
marekmiotelka
commented
Nov 16, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment