I want to set some products category programmatically. When a new product is published it's working. But when i can update it, it's showing an error like: Backend fatal error: PHP Fatal error: Cannot use object of type WP_Error as array in plugins/custom-sync-products/trade_functions.php on line 100\n.Any one help me how to solve this error.

function set_product_category_woo($T_product_type,$post_id){

    $product_categories = term_exists($T_product_type,"product_cat");

        $slug=str_replace(" ","_",$T_product_type);
        $resp=wp_insert_term($T_product_type,'product_cat',array('description'=> '','slug' =>$slug));

        /****assign category to the product in woo***/
            wp_set_object_terms($post_id,$resp['term_id'], 'product_cat' );
  • Some time this error is occured:WP_Error Object ( [errors] => Array ( [empty_term_name] => Array ( [0] => A name is required for this term. ) ) [error_data] => Array ( ) ) – H.Jaware Sep 26 '18 at 12:04
  • wp_insert_term does internally a wp_unslash and a trim for the name. – realloc Sep 26 '18 at 13:37
  • I added some code to illustrate what I mean. – realloc Sep 26 '18 at 13:51

wp_insert_term returns an array on success or a WP_Error in case of problems.

You should catch the error and look for the reason why it fails.

One problem could be, how you create the slug, because it could lead to an error during the creation of the term. Just use $slug = sanitize_title( $T_product_type ) or - even better - let the function wp_insert_term create a unique slug for you.

Another thing is the name itself. Based on what I wrote before I would propose to change your code like this:

function set_product_category_woo( $T_product_type, $post_id ) {
    $name = trim( stripslashes( $T_product_type ) );
    if ( empty( $name ) ) {

    $product_categories = term_exists( $name, 'product_cat' );
    if ( empty( $product_categories ) ) {
        $resp = wp_insert_term( $name, 'product_cat' );

        if ( ! is_wp_error( $resp ) ) {
            wp_set_object_terms( $post_id, $resp['term_id'], 'product_cat' );

        // rest of your code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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