WordPress Snippet: Creating an action endpoint

90% of my WordPress based work is API integrations and back-end systems integration work. It’s important to be able to quickly and easily have two systems speaking to each other.

Outside of the typical WordPress REST API, you can easily create a custom URL that your external integration can call in a few lines of code.

It’s working!

Prerequisites:

  • A plugin with a class.
  • An action name.

Inside the class constructor (__construct()), create the bare endpoints. We’re using action name ‘updateDocument’.

add_action('wp_ajax_updateDocument', array($this, 'updateDocument_callback'));
add_action('wp_ajax_nopriv_updateDocument', array($this, 'updateDocument_callback'));

The first line says “When an authenticated user requests ‘/wp-admin/admin-ajax.php?action=updateDocument’ run the ‘updateDocument_callback’ method in this class”.

The second line allows unauthenticated users (this is important, API requests will typically not use WordPress authentication).

Now, create the function as a method in your class, which at this stage should look like:

function updateDocument_callback()
{
    echo "It worked!";
    die();
}

Now, when you visit https://(your-site)/wp-admin/admin.ajax.php?action=updateDocument (the action endpoint), it should say “It worked!”.

Now that you’ve got this all wired up, there’s a few more important steps before you’re ready for production here.

  • Authentication. How will you verify the person visiting the URL is allowed to? Token based authentication is an easy solution here, google “Authorization: Bearer” for a few options.A common pattern is to base64 encode the user ID and a secret key. (Always transmit over HTTPS to avoid credential leaking!)

    It’s easy to start adding endpoints to your plugin or application and leave authentication for later, which is a hack waiting to happen.

  • Testing. Make sure you write unit and integration tests for this endpoint, to prove it does what you say it does. Include an unauthenticated request in your test to ensure it rejects invalid users.
  • Functionality. Because you’ve added this to a WordPress plugin, you’ve got the whole kitchen sink of WordPress available at your disposable, including all your wordpress plugins, $wpdb, etc.
    You’ve also got direct access (via $_GET and $_POST) to any data you submitted to the endpoint.

Leave a Reply

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