WordPress process form request from external website by plugin

I would like to create an endpoint similar to

http://localhost/wordpress/xxxx/ 

that whenever is called is processing POST request.
So my situation looks like:

Read More

Site A Web Form -> User submits data ->
Wordpress (http://localhost/wordpress/xxxx/ ) -> I am parsing and processing request

How can I achieve it without calling plugin files directly ?
It seems that the simplest way to detect if the ‘xxxx’ is used as a part of url is to use parse_request:

add_action('parse_request', 'xxxx_parse_request');
function xxxx_parse_request($wp) {

    if (array_key_exists('xxxx', $wp->query_vars)) {
                        $location =  plugin_dir_url(__FILE__).'includes/issuer_json.php';
                // process the request.
         wp_redirect($location);
    }
}

but it works only with requests like wordpress?xxxx=1 but not with wordpress/xxxx. I thought that it would work for me and I created a test form to check it. Note that I specify the action of the form to be http://localhost/wordpress/?xxxx=1 and specified a hidden input to test passing the data.

<form action="http://wordpress/?xxxx=1"> 
<input type="hidden" name="test" value="tes1"/>

<input type="submit" />
</form>

Whenever I submit the form, I am redirected to the page with url like: http://wordpress/?test=tes1 so the form overwrote the default action http://wordpress/?xxxx=1

I am not sure how to deal with the problem. Any help will be appreciated.

Related posts

Leave a Reply

1 comment

  1. I seems to me that you need to use the WP admin-ajax handler.

    Basically in your plugin you create something like:

    add_action( 'wp_ajax_my_plugin_function', 'my_plugin_function' );
    
    function my_plugin_function() {
        // Handle request then generate response using WP_Ajax_Response
        echo "You reached my plugin function";
        // important!
        exit();
    }
    

    then in your ajax or form action you POST to http://mydomain.com/wp-admin/admin-ajax.php with a POST parameter (or hidden input) called action with value ‘my_plugin_function’.

    I don’t often submit forms directly but using jQuery AJAX it would be something like:

    $.ajax({
        type: "POST",
        url: "http://mydomain.com/wp-admin/admin-ajax.php",
        data: {'action' : 'my_plugin_function, 'myvar':'another_var'},
        error: function(jqXHR, textStatus, errorThrown){                                        
            console.error("The following error occured: " + textStatus, errorThrown);                                                       
        },
        success: function(data) {                                       
            console.log("Hooray, it worked!");                                                                  
        }
    });
    

    you can find more info in http://codex.wordpress.org/AJAX_in_Plugins