I am running some of the WP functions directly inside a plugin, including wp_insert_post(), if something goes wrong, this returns a WP Error object, what is the correct method to catch this error? Either using built in WP functions or PHP exceptions or whatnot..

-
Assign return of the function to the variable.
-
Check the variable with
is_wp_error()
. -
If
true
handle accordingly, for exampletrigger_error()
with message fromWP_Error->get_error_message()
method. -
If
false
– proceed as usual.
Usage:
function create_custom_post() {
$postarr = array();
$post = wp_insert_post($postarr);
return $post;
}
$result = create_custom_post();
if ( is_wp_error($result) ){
echo $result->get_error_message();
}