Use a PHP file as action for a form in a WordPress plugin, what’s the correct way?

To be honest, you should never use a PHP file as action attribute for a form in WordPress. WordPress already has API for this and you should use this instead. Why? Because it’s always better if your app/site has only one entry point (or as few as possible).

And it’s always a bad idea to direct any PHP requests directly to wp-content directory – such requests are very often blocked for security reasons.

So how to do this properly?

Use admin-post instead.

So in your form change this:

<form action="<SOME FILE>" ...

to this:

<form action="<?php echo esc_attr( admin_url( 'admin-post.php' ) ); ?>" ...
    <input type="hidden" name="action" value="myform" />

And later in your plugin, you have to register your actions callbacks:

add_action( 'admin_post_myform', 'prefix_admin_myform_callback' );
add_action( 'admin_post_nopriv_myform', 'prefix_admin_myform_callback' );


function prefix_admin_myform_callback() {
    status_header(200);
    die("Server received '{$_REQUEST['data']}' from your browser.");
    //request handlers should die() when they complete their task
}

Leave a Comment