Cannot use object of type WP_Error as array

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.

tech