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 comments
Comments are closed.
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:
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.
Seems like you’re asking for a couple of things. I’ll try my best to help.
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
You’ll need a .htaccess rule to direct all requests for a particular url pattern to a certain script. What would make sense to me is matching
api/version_number/api_resource
to a particular php script.Example: Use .htaccess to map
api/v1/user
requests towp-contentthemesyour_themeapiv1user.php
. Now your user can dowww.philosophyguy.com/api/v1/user?id=1337&action=upvote
and your script will upvote user #1337. You can set it up to collect POST requests instead of GET. Or both, if you like. It all depends on youruser.php
file.Here’s a snippet from a recent project that pretty much does the same thing.
<?php
This script will run silently (i.e., no HTTP output)
<?php
?>
Now there’s no need to create a custom WordPress template to handle this operation. It’s all being managed separately outside of the WordPress environment. To do the necessary save and update WordPress stuff, there’s a few guides on how to load up the WordPress environment externally. I think this one will help tons.