Thursday, December 24, 2015

Displaying Errors from the save_post Hook in WordPress

Despite the existence of WP_Error and all the pieces required, there is no single “WordPress Way” to handle and display errors. You can indicate an error occurred in a function or method by returning the WP_Error object (and that’s been my usual MO in my work), but once we do, how do we handle these error objects?

WordPress Errors

It’s easy on the AJAX side of things: Use wp_send_json_{error/success} and handle the response accordingly. However, a common area where generated errors need to be displayed to the user is on the save_post hook, which is actually slightly more complicated than it looks.

The reason for this is due to the way WordPress handles saves. If you’re on a page like post.php?post=1234 and you make your edits and hit save, WordPress POST’s the information to post.php. After the save_post hook fires, everything that’s done is done, it then redirects back to the post.php?post=1234 editor page.

This makes things difficult because the redirect means the execution thread for loading the editor page isn’t the same as the thread for saving the post, and we no longer have access to the same global variables we did when we were saving. Because of this, we need a way to pass that information from the action to the page we’re being redirected to.

Let’s walk through 3 potential methods of solving this problem. I’ll explain how to implement each one, point out some of their pros and cons, and explain to which contexts they’re best suited.

Continue reading %Displaying Errors from the save_post Hook in WordPress%


by James DiGioia via SitePoint

No comments:

Post a Comment