Cannot use object of type WP_Error as array

Using a WordPress Plugin WPML I have been getting this error on saving a draft post:

PHP Fatal error:  Cannot use object of type WP_Error as array in /home/user/domain.com/wp-content/plugins/sitepress-multilingual-cms/inc/taxonomy-term-translation/wpml-term-translations.class.php on line 1018

On that line I have

    $new_term = wp_insert_term( $term_name, $taxonomy, array( 'slug' => self::term_unique_slug( sanitize_title( $term_name ), $taxonomy, $post_lang ) ) );
if ( isset( $new_term[ 'term_taxonomy_id' ] ) ) {
                                $ttid_in_correct_lang = $new_term[ 'term_taxonomy_id' ];
                                $trid                 = false;
                                if ( $bulk ) {
                                    $trid = $sitepress->get_element_trid( $ttid, 'tax_' . $taxonomy );
                                }
                                $sitepress->set_element_language_details( $ttid_in_correct_lang, 'tax_' . $taxonomy, $trid, $post_lang );
                            }
                        }

In another thread I read about a similar issue, but not quite the same where a plugin was trying to access an object as an array.
Any ideas how I could work this out?

1 Answer
1

Well, it’s pretty clear, why this problem occurs.

Let’s look at wp_insert_term documentation:

Return Values

(array|WP_Error)
The Term ID and Term Taxonomy ID. (Example: array(‘term_id’=>12,’term_taxonomy_id’=>34))

As you can see, on success this function returns array. But… If any error occurs, it will return an object of WP_Error type.

So… This Fatal Error occurs, because wp_insert_term ends with error and the rest of code doesn’t process it correctly.

The simple way to fix this is adding another condition to your if statement like this:

$new_term = wp_insert_term( $term_name, $taxonomy, array( 'slug' => self::term_unique_slug( sanitize_title( $term_name ), $taxonomy, $post_lang ) ) );
if ( !is_wp_error($new_term) && isset( $new_term[ 'term_taxonomy_id' ] ) ) {
    ...

But this won’t solve the real problem – the error occurring in wp_insert_term call.

Leave a Comment