Skip to content

Instantly share code, notes, and snippets.

@CesarBenavides777
Created April 5, 2023 15:01
Show Gist options
  • Save CesarBenavides777/82a04fc07405ba399502f806348d211d to your computer and use it in GitHub Desktop.
Save CesarBenavides777/82a04fc07405ba399502f806348d211d to your computer and use it in GitHub Desktop.
Gravity Forms + WPGraphQL + ACF
<?php
add_action('acf/init', 'my_acf_init');
// Removing <p> tags
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
// Gravity Forms ACF
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((int) $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);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment