fix: decode HTML entities in posts widget titles and excerpts

WordPress's get_the_title() returns HTML-encoded entities (e.g., ’
for smart quotes). Since the React component renders via createElement
(textContent, not innerHTML), these entities displayed as raw text.

Fix applied at two levels:
- PHP REST endpoint: html_entity_decode() before sending JSON response
- JS PostCard component: decodeEntities() safety net for any residual
  encoded entities from other sources

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Terence Ong
2026-04-13 14:33:51 +07:00
parent 943e7dff8c
commit 46d3a35c3a
2 changed files with 45 additions and 4 deletions

View File

@@ -96,6 +96,38 @@
return Math.max(1, Math.round((wordCount || 0) / 250));
}
/**
* Decode HTML entities in a string (e.g., &#8217; → ').
*
* Uses a DOMParser to safely decode entities without executing scripts.
* Falls back to common entity replacements if DOMParser is unavailable.
*
* @param {string} text Text that may contain HTML entities.
* @return {string} Decoded plain text.
*/
function decodeEntities(text) {
if (!text) {
return '';
}
if (typeof DOMParser !== 'undefined') {
var doc = new DOMParser().parseFromString(text, 'text/html');
return doc.body.textContent || '';
}
// Fallback: decode common entities manually.
return text
.replace(/&#8217;/g, '\u2019')
.replace(/&#8216;/g, '\u2018')
.replace(/&#8220;/g, '\u201C')
.replace(/&#8221;/g, '\u201D')
.replace(/&#8211;/g, '\u2013')
.replace(/&#8212;/g, '\u2014')
.replace(/&amp;/g, '&')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#039;/g, "'");
}
/**
* Strip HTML tags from a string.
*
@@ -124,6 +156,7 @@
var post = props.post;
var catClass = getCategoryClass(post.category_slug);
var minutes = readingTime(post.word_count);
var title = decodeEntities(post.title);
var excerpt = stripHtml(post.excerpt);
// Choose placeholder icon based on category
@@ -132,7 +165,7 @@
return el('a', {
href: post.url || '#',
className: 'prab-post-card',
'aria-label': post.title
'aria-label': title
},
// Image area
post.featured_image
@@ -161,7 +194,7 @@
),
// Title
el('h3', { className: 'prab-post-title' }, post.title),
el('h3', { className: 'prab-post-title' }, title),
// Excerpt
el('p', { className: 'prab-post-excerpt' }, excerpt),