How To Use WordPress Functionality From a Bespoke PHP Script
As a WordPress developer there might come a time when you need to write a bespoke PHP script that sits outside of the WordPress file structure, yet needs to use the standard functionality available from within the CMS.
This was exactly the scenario I found myself in recently, whereby a completely custom script would take data records from a third-party data source and import them into WordPress as posts at regular intervals.
A lot of people at this point are probably thinking ‘why not do it as a plugin?’. Well, I could have done but I decided against this because:
a) Active plugins in WordPress are loaded, or at least referenced, each time a page is requested. Considering I only wanted my script to run once a day this seemed a bit extreme.
b) People with admin rights would have access to deactivate it, or even worse delete it, from the ‘Plugins’ section of WordPress.
Custom script it was. I set up a new file in the root of my site and I was ready to get to work.
So, how do we load the same functionality that exists in WordPress in a bespoke script? The secret lies in the /wp-load.php file which we can include in PHP like so:
This is essentially what happens when any page request is made in WordPress. If you open up your WordPress index.php file in the root directory, you will see it includes wp-blog-header.php, which then in turn includes wp-load.php.
We’re now essentially doing the same thing, but skipping out the bit that deals with themes and templates.
Using The WordPress Functionality
Now that we’ve got WordPress loaded, we can do pretty much anything we want in this script that we would do in our theme or plugin. For example, to add a post our script might look like so:
require_once("./wp-load.php"); // Create post / property object $new_post = array( 'post_title' => 'My Post From The Outside', 'post_status' => 'publish', 'post_type' => 'post', 'post_author' => 1 ); // Insert the post into the database $property_post_id = wp_insert_post( $new_post );
Simple huh? I hope that helps you on your way if you’re thinking about building a bespoke script to interact with WordPress.