Skip to content

Instantly share code, notes, and snippets.

@esamattis
Last active July 24, 2024 18:10
Show Gist options
  • Save esamattis/54abd801b078056f9e646d63d47ccc4c to your computer and use it in GitHub Desktop.
Save esamattis/54abd801b078056f9e646d63d47ccc4c to your computer and use it in GitHub Desktop.
Automatically decode HTML entities from wp-graphql content fields
<?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;
}
}
@esamattis
Copy link
Author

esamattis commented Dec 13, 2019

Usage in functions.php:

require_once __DIR__ . '/HTMLEntities.php';

(new HTMLEntities())->init();

@sloyer
Copy link

sloyer commented Feb 12, 2021

Thank you for this

@esamattis
Copy link
Author

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