The first problem I see with you code is that you are assuming that $_POST['mh_action']
is a string, coming from $_POST
you can never be sure that's true.
And if that's an array, you could not do sanitize_text_field( $_POST['mh_action'] )
without triggering an error.
Second problem is that do_action
returns nothing. It means that you are changing super global $_POST
directly, which I strongly suggest you to avoid.
One of the many reasons is that the piece of code that processes data would need to access to $_POST
and even if you sanitized using the action, looking only at the code that make used of data, that would not be unclear.
Moreover, some other code (maybe malicious, maybe not) could always remove_action( 'mh_foo' )
and your "foo" field would never be escaped, and so the code that access $_POST['mh_foo']
and processes it, would process potentially unsafe data.
What you should do is to take the data from $_POST
, extract the data of interest, validate them (what is expected to be a string is a string...) after that you can pass the validate data as argument to the processing function, where you can first sanitize it and then make use of it, eg. store, display...
Just a proof of concept:
function mh_post_action() {
$action = isset($_POST['mh_action']) ? $_POST['mh_action'] : '';
if ( ! $action ) {
return;
}
$validated_action = mh_post_action_validate( $action );
if ( ! $validated_action ) {
// handle the error
return;
}
mh_post_action_process( $validated_action );
}
function mh_post_action_validate( $action ) {
// as example I'm validating it is a string that starts with "mh_"
if ( is_string( $action ) && strpos( $action, 'mh_' ) === 0 ) {
return $action;
}
return '';
}
function mh_post_action_process( $action ) {
$sanitized_action = sanitize_text_field( $action );
// process sanitized_action here
}
add_action( 'init', 'mh_post_action' );
Now if I look at mh_post_action
I can clearly see that data coming from $_POST
is being validated, and I can clearly see that mh_post_action_process()
sanitize data before doing anything with it.
I think that you can easily convert your existing function to follow such scheme and you will improve readability of your code (that is good for you), its understandability (that is good for the wp.org review team) and its security (that is good for everyone).