I need to create a PHP script that will receive data from another application via an HTTP post, process that data, and update the WordPress database. This script will run silently (i.e., no HTTP output). What is the best way to set up such a page? I thought about creating a custom template file with the PHP script and assigning that template to a blank WordPress page, but is there a better method I should use?

2 Answers
2

I would use the Rewrite API and the template_redirect action to respond to API requests.

As an example, if I wanted to respond to requests directed to the url: example.com/example-path/ with logic in my theme or plugin’s endpoint.php file I would create a rewrite rule and template redirect hook like so:

add_action( 'init', 'example_rewrite_rules' );
add_action( 'template_redirect', 'example_template_route' );

/**
 * Add rewrite rules for Example endpoint.
 */
function example_rewrite_rules()
{
    add_rewrite_rule(
        'example-path/?$',
        'index.php',
        'top'
   );
}

function example_template_route( $default_template ) {
    global $wp, $wp_rewrite;

    if ( $wp->matched_rule == 'example-path/?$' ) {
        // call function or include template view here.
        include dirname( __FILE__ ) . '/endpoint.php';
        exit();   
    }
}

Depending on the data being posted from your API you may also want to add a rewrite_tag to be able to access query strings passed to your example-path route.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *