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..

3

  1. Assign return of the function to the variable.

  2. Check the variable with is_wp_error().

  3. If true handle accordingly, for example trigger_error() with message from WP_Error->get_error_message() method.

  4. 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();
}

Leave a Reply

Your email address will not be published. Required fields are marked *