0

I'm getting the fatal error "Critical Object of class WP_Error could not be converted to string".

The theme is developed with twig and php files, to separate logic from visual. Somehow, in the frontend, there's no error, but I receive everyday this fatal error in the logs.

The error is in single-color.php:

$term = wp_get_post_terms( $colection->posts[0]->ID ,'look' ); 

echo'<span property="itemListElement" typeof="ListItem"><a property="item" typeof="WebPage" title="Go to '.$term[0]->name.'"href="'.get_term_link( $term[0]->term_id).'" class="home"><span property="name">'.$term[0]->name.'</span></a><meta property="position" content="3"></span> > ';

Is there anyway to deal with this situation, just to avoid the logs?

1 Answer 1

1

wp_get_post_terms() returns a WP_Error on failure. (Are you sure it's $colection and not $collection in that function call?)

You can check the return value using is_wp_error() and decide what you're going to output if it is, in fact, a WP_Error.

For example:

$term = wp_get_post_terms( $colection->posts[0]->ID ,'look' ); 

if ( is_wp_error( $term ) ) {

    echo 'Error: ' . $term->get_error_message();

} else {

    echo '<span property="itemListElement" typeof="ListItem">
          <a property="item" typeof="WebPage" title="Go to ' .
          $term[0]->name . '"href="' . 
          get_term_link( $term[0]->term_id).'" class="home">
          <span property="name">'.$term[0]->name.'</span>
          </a>
          <meta property="position" content="3"></span> > ';
    // Lines broken up for readability

}
2
  • 1
    I know colection should have two "l" but the variable was defined as "colection". Anyway, your suggestion worked. The fatal error doesn't exist anymore. Thank you. Commented Mar 6, 2023 at 9:35
  • Glad you got it fixed. (I only asked about $colection because I know sometimes it's hard to find the typos in your own code.)
    – Pat J
    Commented Mar 6, 2023 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.