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..
Leave a Reply
You must be logged in to post a comment.
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:
Hei,
first, you check weather your result is a
WP_Error
object or not:This is the usual way.
But the WP_Error object can be instanciated without any error occuring, just to act as a general error store just in case. If you want to do so, you can check if there are any errors by using
get_error_code()
:If you do that, you can then check for an process the returned error just as in the
wp_insert_post()
example above.The Class is documented on the Codex.
And there’s also a little article here.
This will show you exactly what’s wrong with wordpress post insert function. just try it !