Plugin Form Submission Best Practice

I have done a lot of researching and haven’t found quite what I am looking for, so I am hoping that I can be pointed in the right direction.

I am developing an Events plugin that will book a ticket from the frontend. This is no different than any other Form submission, but what I am getting confused with is how to handle that from a plugin that is written via OOP with a class.

Most articles that I found say to put the $_POST handling within the template page. Ideally I would like to have this handled by a function within the plugin.

The other thing that I am not sure about is when you submit the form on the frontend, how that actually gets passed to the function on the backend. I am hoping to completely abstract the form processing from any template details.

// events.php
if ( ! class_exists( 'Events' ) ) {

    Class Events {
        function __construct() {
            add_action( 'plugins_loaded', array( &$this, 'includes' ), 1 );
        }

        function includes() {
            require_once( EVENTS_INCLUDES . 'functions.php' );
        }
    }
}

if ( class_exists( 'Events' ) ) {
    $events_load = New Events();
}


// functions.php
function process_form() {
    ...do form processing here...

    ...insert booking...
}

I’m not sure what to hook into that would catch that, or where to send the form action too. Thanks for all the help!

-Adam

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Send the form action either to your homepage, or to a specific page URL. You can’t have $_POST handling within the template because you need to redirect after your process it, and redirect needs to be fired before any HTML output.

// you should choose the appropriate tag here
// template_redirect is fired just before any html output
// see - http://codex.wordpress.org/Plugin_API/Action_Reference
add_action('template_redirect', 'check_for_event_submissions');

function check_for_event_submissions(){
  if(isset($_POST['event'])) // && (get_query_var('pagename') === 'events) 
    {
       // process your data here, you'll use wp_insert_post() I assume

       wp_redirect($_POST['redirect_url']); // add a hidden input with get_permalink()
       die();
    } 

}

You could also check for a nonce to make sure the data was submitted from the right place…


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x