Using WordPress ‘convert_invalid_entities()’ PHP function

The convert_invalid_entities() WordPress PHP function converts invalid Unicode references range to valid ones.

Usage

Let’s assume you have a string that includes some invalid Unicode entities. You can use the convert_invalid_entities() function to correct these. Here’s how you might do that:

$content = "Invalid Unicode: 🦁"; // some invalid Unicode entity
$converted_content = convert_invalid_entities($content);
echo $converted_content; // Output: the corrected Unicode entity

Parameters

  • $content (string): This is the string that contains the entities needing conversion.

More information

See WordPress Developer Resources: convert_invalid_entities()

Please note that this function is part of the WordPress core and is used internally. It’s recommended to use higher level WordPress functions for most use cases.

Examples

Correcting a single Unicode entity

This code corrects a single invalid Unicode entity in a string.

$content = "Hello 🦁 World"; 
$converted_content = convert_invalid_entities($content); 
echo $converted_content; // "Hello (corrected Unicode entity) World"

Correcting multiple Unicode entities

This code corrects multiple invalid Unicode entities in a string.

$content = "🦁 Hello 🦁 World 🦁"; 
$converted_content = convert_invalid_entities($content); 
echo $converted_content; // "(corrected Unicode entity) Hello (corrected Unicode entity) World (corrected Unicode entity)"

Correcting Unicode entities in HTML content

This code corrects invalid Unicode entities within an HTML string.

$content = "<p>Hello &#129409; World</p>"; 
$converted_content = convert_invalid_entities($content); 
echo $converted_content; // "<p>Hello (corrected Unicode entity) World</p>"

Correcting Unicode entities in a WordPress post

This code corrects invalid Unicode entities within the content of a WordPress post.

global $post;
$content = $post->post_content;
$converted_content = convert_invalid_entities($content);
echo $converted_content; // Outputs the corrected post content

Correcting Unicode entities in a user comment

This code corrects invalid Unicode entities within a comment from a user.

$comment = get_comment_text(); 
$converted_comment = convert_invalid_entities($comment);
echo $converted_comment; // Outputs the corrected comment text

Tagged in

Leave a Comment

Your email address will not be published. Required fields are marked *