Setting up an API “listening” page

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.

Leave a Comment