Search code examples
wordpressformssubmitshortcode

How elaborate input of a WordPress shortcode form ($_POST array)?


I'm trying to create a custom WordPress shortcode to generate a form. I wrote a function ( called send_advice_request_form() ) that returns HTML form code, then the callback that use ob_start() and return ob_get_clean(), how can I elaborate submitted form data? If I don't indicate any action attribute for form, where the post data will be submitted?

function send_advice_request_form_cb() {

    ob_start();

    echo send_advice_request_form();

    return ob_get_clean();

}
add_shortcode( 'dparequestform', 'send_advice_request_form_cb' );

function send_advice_request_form() { //return HTML form }

Solution

  • The best way for handling custom form like yours is to send the datas to admin-post.php

    Create a form with this action and this input type hidden :

    <form action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
      /*
         Your fields here.
      */
    
       <input type="hidden" name="action" value="your_action_name">
    </form>
    

    Then you will have to handle datas with those hooks

    function send_advice_request_handler() {
    
        /*
           Do what you have to do.
        */
    }
    
    // Hook for everyone, no private
    add_action( 'admin_post_nopriv_your_action_name', 'send_advice_request_handler' );
    
    // Hook only for logged in users (verified by wordpress with is_user_logged_in())
    add_action( 'admin_post_contact_form', 'send_advice_request_handler' );
    

    I hove it will helps you, tell me if you need more help.