admin管理员组

文章数量:1391999

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/multimedia-2/wp-content/plugins/imdb/imdb.php on line 11

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/multimedia-2/wp-content/plugins/imdb/imdb.php on line 11

Share Improve this question edited Apr 4, 2020 at 8:10 Chetan Vaghela 2,4084 gold badges10 silver badges16 bronze badges asked Apr 4, 2020 at 6:30 aliali 456 bronze badges 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 – 西門 正 Code Guy - JingCodeGuy 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 – 西門 正 Code Guy - JingCodeGuy 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/multimedia-2/wp-content/plugins/imdb/imdb.php on line 11 – ali Commented Apr 4, 2020 at 7:42
Add a comment  | 

1 Answer 1

Reset to default 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'];
}

本文标签: wp errorCannot use object of type WPError