In your action callback, if validation fails, create a new WP_Error
object with an appropriate message and return that object. WP will handle the rest. This does not work for all actions, but it does with “pre_insert_term”.
Hey @bcworkz thanks for the reply! However, I’m not following. I think that’s exactly what I’m doing, e.g.:
add_filter('pre_insert_term', function ($term, $taxonomy) {
return new \WP_Error('test_fail', 'Test fail!', [
'status' => 400,
]);
}, 10, 2);
The POST response returns a 400 and I see the custom error code and message in the Chrome Inspector, but there’s no notification to the user on /wp-admin/post-new.php that adding the term failed. I am expecting a modal, or message near the taxonomy interface. What am I missing?
By the way, that code is running on 5.8.1.
Thanks again!
-
This reply was modified 2 years, 8 months ago by tmfhokies.
Huh, your code works on my site. Message shows up near the top of the terms edit screen, right below “Categories” in my testing. Works in a custom taxonomy as well.
Perhaps your theme or other code is interfering? Test with no active plugins except the relevant code and Twenty Twenty-one theme.
@bcworkz Thanks again for taking a look. I deactivated all other plugins and switched to the Twenty Twenty-one theme.
The code snippet above produces the expected error message on /wp-admin/edit-tags.php?taxonomy=post_tag. Here’s a screenshot: https://i.imgur.com/A7XGSP6.jpg.
However, I don’t see any error when adding a tag via /wp-admin/post-new.php.
No error message: https://i.imgur.com/EBzzpZN.jpg
400 response because of pre_insert_term
filter: https://i.imgur.com/UGMZfTf.jpg
Does an error message show for you on /wp-admin/post-new.php?
No, I have the same experience, adding a term just fails to work with no notification. The API request does return the WP_Error object in JSON format, but the requesting script doesn’t appear to know what to do with it. The script is in the minified version of /wp-includes/js/dist/api-fetch.js. The applicable function can likely be overridden to behave differently, but I’m unsure of the specifics. JavaScript isn’t my strong suit.
The applicable function can likely be overridden to behave differently, but I’m unsure of the specifics.
What do you mean by overridden?
I’ve looked at the code and I don’t see anyway to override with a client-side hook. Though I am much more familiar with back-end code, so it’s possible I am missing something myself.
The API request does return the WP_Error object in JSON format, but the requesting script doesn’t appear to know what to do with it.
Honestly, this feels like something core should handle out of the box.
In JavaScript we can override functions by re-declaring one with the same name, but ensuring it loads later.
Please consider submitting a bug report in the WP Trac system so this can be properly tracked.
https://core.trac.wordpress.org/newticket