Cannot use object of type WP_Error

function im_add_new_term($name,$tax){   
    if($tax == "genre"){      
        return wp_insert_term($name,$tax,array("slug"=array_search ($name, $genres)))["term_id"];  
    } else {
        return wp_insert_term($name,$tax)["term_id"]; 
    }
}

Fatal error: Cannot use object of type WP_Error as array in /home/pcodecom/demo.p30code.com/multimedia-2/wp-content/plugins/imdb/imdb.php on line 11

Topic wp-error Wordpress

Category Web


What's $genres? I don't see it defined anywhere.

And wp_insert_term() may return an error, so make sure to check if it is an error. So instead of simply doing return wp_insert_term($name,$tax)["term_id"], you could do something like this:

$data = wp_insert_term( $name, $tax );
if ( ! is_wp_error( $data ) ) {
    return $data['term_id'];
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.