I have a plugin with a setting page, and there are some action that have to be done when a certain option is saved. I am using the pre_update_option_
hook to do this. So far so good. If something goes wrong, however, I’d also need to notify that to the user.
I tried these things:
1) Add hook to admin_notices before updating the code
add_action ('pre_update_option_my_var', function( $new_value, $old_value) {
//Do my validation
$valid = ( 'correct_value' == $new_value );
if ( !$valid ) add_action('admin_notices', 'my_notification_function' )
return ($valid)? $new_value : $old_value;
});
The validation works, but the notification is not displayed because, I assume, by then the functions hooked to admin_notices
have already been executed?
2) Validation in the function hooked to admin_notices
To solve the problem above, I had this idea.
add_action('admin_notices', function () {
//Do my validation
$valid = ( 'correct_value' == $_POST['my_var'] );
if (!$valid) { /* Display error message */ }
//Store the value of $valid
});
add_action ('pre_update_option_my_var', function( $new_value, $old_value) {
//fetch the value of $valid which I stored
return ($valid)? $new_value : $old_value;
});
Now, this would seem to work well, I do see the notification now. The problem is that for some strange reason I don’t see the posted values. I tried to print $_POST
and it always empty! Probably WordPress is passing the values in some other way? If so, how?
Which one is the right way to go, and how can I fix the issue? Of course, if any other method is better than these two and solves the issue, it’s welcome.