Using WordPress ‘convert_chars()’ PHP function

The convert_chars() WordPress PHP function converts standalone ‘&’ characters into ‘&’ (also known as ‘&’).

Usage

convert_chars($content, $deprecated = '');

In this example, $content is a string of characters that will be converted, and $deprecated is not used, but exists for backward compatibility.

Parameters

  • $content (string) – Required. The string of characters to be converted.
  • $deprecated (string) – Optional. This parameter is not used and is defaulted to an empty string (”).

More information

See WordPress Developer Resources: convert_chars
This function is a part of WordPress core and is used widely. As of the latest version, it has not been deprecated.

Examples

Converting a Simple String

In this example, we’ll convert a simple string with ‘&’ characters. After running the function, every standalone ‘&’ character will be converted into ‘&’.

// Define a string with '&' characters
$string = "Fish & Chips & Vinegar";

// Use the function to convert '&' characters
$converted_string = convert_chars($string);

// Output the converted string
echo $converted_string; // Outputs: "Fish & Chips & Vinegar"

Converting a String in a Post

Assuming you have a post with ‘&’ characters in the content, you can convert them using this function.

// Assume you have a post
$post_content = get_the_content();

// Convert '&' characters in the post content
$converted_content = convert_chars($post_content);

// Output the converted content
echo $converted_content;

Using in a Post Loop

You can apply this function directly in a WordPress post loop to convert ‘&’ characters in all posts’ content.

// Start the loop
if ( have_posts() ) : while ( have_posts() ) : the_post();

    // Get the content and convert '&' characters
    $converted_content = convert_chars(get_the_content());

    // Display the converted content
    the_content($converted_content);

endwhile; endif;

Converting HTML Entities

This function also converts HTML entities. Here’s how you can use it:

// Define a string with HTML entities
$string = "5 > 3";

// Convert HTML entities
$converted_string = convert_chars($string);

// Output the converted string
echo $converted_string; // Outputs: "5 > 3"

Converting a String with Multiple ‘&’ Characters

This function can handle strings with multiple ‘&’ characters as well.

// Define a string with multiple '&' characters
$string = "Fish & Chips & Vinegar & Salt";

// Convert '&' characters in the string
$converted_string = convert_chars($string);

// Output the converted string
echo $converted_string; // Outputs: "Fish & Chips & Vinegar & Salt"