2
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

5
  • Cannot use object of type WP_Error as array means you cannot call it with array notation like $something['term_id'], instead, you need to call it with arrow notation like $someting->term_id Commented Apr 4, 2020 at 6:37
  • wp_insert_term($name,$tax)->term_id ok?
    – ali
    Commented Apr 4, 2020 at 6:47
  • it might work in new PHP, but in old php it might not work. For better compatibility, it is better to create a variable first then use the variable to get the value Commented Apr 4, 2020 at 7:25
  • function im_add_new_term($name,$tax){ if($tax == "genre"){ $ali = wp_insert_term($name,$tax,array("slug"=>array_search ($name, $genres))); return $ali->term_id; } else { $faraji = wp_insert_term($name,$tax); return $faraji->term_id; } } not working
    – ali
    Commented Apr 4, 2020 at 7:40
  • error : Undefined property: WP_Error::$term_id in /home/pcodecom/demo.p30code.com/multimedia-2/wp-content/plugins/imdb/imdb.php on line 11
    – ali
    Commented Apr 4, 2020 at 7:42

1 Answer 1

1

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'];
}
2
  • What's $genres? Movie genre
    – ali
    Commented Apr 4, 2020 at 9:14
  • Ok, just make sure it's defined in your actual code, because I don't see it defined in the question (e.g. $genres = array( 'foo' => 'Foo' );). :)
    – Sally CJ
    Commented Apr 4, 2020 at 9:20

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.