PHP Catchable fatal error: Object of class WP_Error could not be converted to string

Line 58 as the error indicates is this line:

$parent_term = get_term_by('ID',$term_id, $taxonomy);
$term_parents = $delimiter."<a href=\"".get_term_link($parent_term->slug,$taxonomy)."\" title=\"". $parent_term->name ."\" >". $parent_term->name ."</a>" .$child_terms;

And our error is:

Object of class WP_Error could not be converted to string

Which means that one of those things being appended is not a "string", but actually a WP_Error object.

I would cast suspicion on get_term_link, which is probably what’s returning the error object, which suggests either that the:

  • term doesn’t exist
  • the taxonomy isn’t registered or valid
  • the values being passed are unexpectedly blank
  • $parent_term isn’t a term, but an error object

Which leads us to the lesson here:

Sometimes functions return error objects and you have to check for that, don’t just assume it succeeded

How to Check for Errors

Lets take an example that will always fail:

$value = get_term_link( "not a real term","fake taxonomy" );
if ( is_wp_error( $value ) ) {
    // something went wrong
}

is_wp_error will be true if $value is an error object. Some functions may return false or null, so !empty( $value ) is also a useful check

Error objects can contain error codes and messages, and you can use the get_error_message() method to display them:

$value = get_term_link( "not a real term","fake taxonomy" );
if ( is_wp_error( $value ) ) {
    // something went wrong
    echo $value->get_error_message();
}

You could also set $value manually to a default value instead

A final note on globals

The code makes use of global variables, but these variables have super generic names such as $taxonomy. Other plugins may also use these, and they can clash. The same is true of function names.

Better

Prefix them:

// term parents function
function sergi_term_parents( $term_id, $child_terms ) {
    global $sergi_taxonomy, $sergi_delimiter;

Best

Use dependency injection and eliminate the globals entirely:

// term parents function
function sergi_term_parents( $term_id, $child_terms, $taxonomy, $delimeter ){

Now your term_parents function will never clash, and works for any taxonomy or delimeter

Leave a Comment