How to call WordPress functions from a form processing script

You should never post anything to plugins files directly. It’s almost always a security flaw and it prevents site owner from hardening the site properly (in perfect situation no requests to PHP files inside wp-content should be necessary at all)

Good practice is that you use admin_post actions… (similar to admin_ajax).

So your form should look like so:

<form action="<?php echo esc_attr('admin-post.php'); ?>" method="post">
    <input type="hidden" name="action" value="my_action" />
    <input type="text" name="keyName">
    <input type="submit" value="Update">
</form>

And then in your plugin you add your action method:

add_action( 'admin_post_my_action', 'prefix_admin_my_action' );
add_action( 'admin_post_nopriv_my_action', 'prefix_admin_add_foobar' );

function prefix_admin_my_action() {
    // Handle request then generate response using echo or leaving PHP and using HTML
}

PS. It’s always a good idea to include some nonces inside that form too.

Leave a Comment