Ffile2fix
Sign in Get started

How to fix "Object of class X could not be converted to string"

Fatal error: Uncaught Error: Object of class WP_Error could not be converted to string in /home/user/public_html/wp-content/themes/mytheme/functions.php:142

The code used an object where a string is required, such as echo, string concatenation or a string function, and the class has no __toString() method. PHP cannot guess which property to print, so it throws an Error.

Also appears as: Object of class stdClass could not be converted to string · Object of class DateTime could not be converted to string · Object of class Closure could not be converted to string · Object of class App\Models\User could not be converted to string

Common causes

  • A WordPress function returned a WP_Error object on failure and the code echoed it
  • Echoing a DateTime/DateTimeImmutable object instead of calling ->format()
  • Concatenating a database row object or decoded JSON object into a string
  • Passing an object to string functions like strlen(), str_replace() or htmlspecialchars()
  • Using an object as an array key or in string interpolation

How to fix it

  1. Identify the object and its class. The message names the class. On the reported line, find which variable is being echoed or concatenated.
  2. Handle WP_Error results. Check is_wp_error($result) before using it, then show $result->get_error_message() if you need the text.
  3. Format dates explicitly. Use $date->format('Y-m-d H:i') rather than echo $date.
  4. Output the property you need. For data objects, echo the specific field: $user->name or $row->title.
  5. Add __toString() for your own classes. If an object has a natural string form, implement public function __toString(): string so it can be echoed safely.
  6. Debug-print objects properly. For inspection use print_r($obj, true), var_export() or json_encode($obj), never string concatenation.

PHP / WordPress

$result = wp_insert_post($data, true);
if (is_wp_error($result)) {
    error_log($result->get_error_message());
} else {
    echo 'Created post ' . (int) $result;
}

echo $date->format('Y-m-d');

How to stop it happening again

  • Check for error objects from functions that can return them
  • Type-hint string parameters so mistakes fail early with clear messages
  • Implement __toString() on value objects meant for display

Frequently asked questions

Why does WP_Error show up in this message?

Many WordPress functions return WP_Error instead of throwing exceptions. If you echo or concatenate the return value without checking is_wp_error(), you get this error.

Can I cast the object with (string)?

Only if the class implements __toString(). Otherwise (string) $obj throws the same error.

How is this different from 'Array to string conversion'?

That is a warning for arrays, and PHP prints the word 'Array'. With objects lacking __toString() PHP throws a fatal Error instead.