Using WordPress ‘addslashes_strings_only()’ PHP function

The addslashes_strings_only() WordPress PHP function adds slashes only if the provided value is a string. It’s a handy function when you want to escape certain characters in a string.

Usage

The function is used simply by passing the value as an argument. If the argument is a string, slashes will be added. If not, the value will be returned as is.

$example_string = "Hello, I'm a string!";
$example_number = 12345;

echo addslashes_strings_only($example_string); // Outputs: Hello, I\'m a string!
echo addslashes_strings_only($example_number); // Outputs: 12345

Parameters

  • $value (mixed): The value to add slashes to, if it’s a string.

More information

See WordPress Developer Resources: addslashes_strings_only()
This function is a part of the WordPress core and is always available. It is not deprecated and likely won’t be as it’s an essential tool for handling string values.

Examples

Escaping a string with quotation marks

If you have a string with quotation marks, you can use addslashes_strings_only() to escape them.

$string_with_quotes = "Hello, \"World\"!";
echo addslashes_strings_only($string_with_quotes); // Outputs: Hello, \"World\"!

Using with a variable that might be a string or a number

If you’re unsure whether a variable is a string or a number, addslashes_strings_only() will handle both cases appropriately.

$unknown_variable = "I'm unsure!";
echo addslashes_strings_only($unknown_variable); // Outputs: I\'m unsure!
$unknown_variable = 56789;
echo addslashes_strings_only($unknown_variable); // Outputs: 56789

Using with a string that includes a backslash

The function will add an extra backslash to any existing backslashes in the string.

$string_with_backslash = "Hello\\World!";
echo addslashes_strings_only($string_with_backslash); // Outputs: Hello\\World!

Adding slashes to a string with apostrophes

Apostrophes can also be escaped using addslashes_strings_only().

$string_with_apostrophe = "It's a beautiful day!";
echo addslashes_strings_only($string_with_apostrophe); // Outputs: It\'s a beautiful day!

Using with non-string values

addslashes_strings_only() can be safely used with non-string values, as they will be returned as is.

$array_value = array("Hello", "World!");
echo addslashes_strings_only($array_value); // Outputs: Array