Last active
July 24, 2024 18:10
-
-
Save esamattis/54abd801b078056f9e646d63d47ccc4c to your computer and use it in GitHub Desktop.
Automatically decode HTML entities from wp-graphql content fields
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 | |
/** | |
* WordPress does automatic HTML entity encoding but so does React which | |
* results in double encoding. This reverts the one from WordPress when | |
* the content is requested using wp-graphql making your life as a React | |
* dev easier. | |
* | |
*/ | |
class HTMLEntities | |
{ | |
public function init() | |
{ | |
// Requires this to be merged https://github.com/wp-graphql/wp-graphql-acf/pull/74 | |
add_filter( | |
'graphql_acf_field_value', | |
[$this, 'decode_acf_entities'], | |
10, | |
2 | |
); | |
add_filter( | |
'graphql_resolve_field', | |
[$this, 'decode_entities'], | |
10, | |
8 | |
); | |
} | |
/** | |
* Decode HTML entities from ACF fields | |
*/ | |
function decode_acf_entities($value, $acf_field) | |
{ | |
$text_types = ['textarea', 'text']; | |
if (in_array($acf_field['type'], $text_types)) { | |
return html_entity_decode($value); | |
} | |
if ('link' === $acf_field['type'] && !empty($value)) { | |
$value['title'] = html_entity_decode($value['title']); | |
} | |
return $value; | |
} | |
/** | |
* Decode HTML entities from other applicable fields. | |
* | |
* XXX This is not complete. | |
*/ | |
function decode_entities( | |
$result, | |
$source, | |
$args, | |
$context, | |
$info, | |
$type_name, | |
$field_key | |
) { | |
if (!\is_string($result) || !$result) { | |
return $result; | |
} | |
$decode = false; | |
if ($source instanceof \WPGraphQL\Model\Post) { | |
if ('title' === $field_key) { | |
$decode = true; | |
} | |
} | |
if ($source instanceof \WPGraphQL\Model\MenuItem) { | |
if ('title' === $field_key) { | |
$decode = true; | |
} | |
if ('label' === $field_key) { | |
$decode = true; | |
} | |
} | |
if ($decode) { | |
return \html_entity_decode($result); | |
} | |
return $result; | |
} | |
} |
Thank you for this
This not needed anymore since it's part of the wp graphql core
https://www.wpgraphql.com/filters/graphql_html_entity_decoding_enabled/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage in functions.php: