Skip to content

Instantly share code, notes, and snippets.

@CesarBenavides777
Created August 31, 2023 21:28
Show Gist options
  • Save CesarBenavides777/79b158db8355ddbc349fbf9b3272ae47 to your computer and use it in GitHub Desktop.
Save CesarBenavides777/79b158db8355ddbc349fbf9b3272ae47 to your computer and use it in GitHub Desktop.
WPGraphqlACF - Custom ACF Table Field Extension - For Updated WPGraphQL Plugin
<?php
// ...existing code
// import
use WPGraphQL\Acf\FieldType\Table;
class FieldTypeRegistry {
// ...exising code
Table::register_field_type();
<?php
namespace WPGraphQL\Acf\FieldType;
// In /FieldType Folder
// use GraphQL\Deferred;
use WPGraphQL\AppContext;
class Table {
/**
* Register the custom ACF table field type for WPGraphQL
*
* @return void
*/
public static function register_field_type(): void {
register_graphql_acf_field_type('table', [
'graphql_type' => 'Table',
'resolve' => function ($root, $args, AppContext $context, $info, $field_type, $field_config) {
try {
$value = $field_config->resolve_field($root, $args, $context, $info);
if (empty($value)) {
return null;
}
// Add some basic validation to ensure the structure matches our expectations
if (!isset($value['p']['o']['uh'], $value['h'], $value['b'])) {
throw new \Exception("ACF table field has an unexpected structure");
}
return [
'headerEnabled' => 1 == $value['p']['o']['uh'],
'header' => 1 == $value['p']['o']['uh'] ? array_map(function ($th) {
return $th['c'];
}, $value['h']) : [],
'body' => array_map(function ($row) {
return array_map(function ($cell) {
return $cell['c'];
}, $row);
}, $value['b']),
'caption' => $value['p']['ca'] ?? ''
];
} catch (\Exception $e) {
// Log the exception message for debugging
error_log($e->getMessage());
return null;
}
},
]);
}
}
add_action('graphql_register_types', function () {
register_graphql_object_type('Table', [
'fields' => [
'headerEnabled' => [
'type' => 'Boolean'
],
'header' => [
'type' => [
'list_of' => 'String'
]
],
'body' => [
'type' => [
'list_of' => [
'list_of' => 'String'
]
]
],
'caption' => [
'type' => 'String'
]
],
]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment