How to use WordPress functions in a non-WordPress custom PHP file

I recently came across a scenario where I wanted to make use of some of the many WordPress functions available, but in a non-WordPress custom PHP file. I was building a feature which automatically sends any newly added WordPress ‘property’ custom posts to my clients Facebook page, using the Facebook PHP SDK.

To achieve this, I wanted to loop through the ‘property’ custom posts using WP_Query and post each newly added property to the Facebook page. This file needed to sit on the root of my site. I starting coding this file up and soon realised I’d forgotten one important thing…I wasn’t working on one of your standard ‘page’, ‘category’, ‘single’ etc WordPress files, therefore I couldn’t use any of the WordPress functions.

After some research, I learnt that the all important WordPress file that I needed to include in my custom PHP file was ‘wp-load.php’. All you need to do is include this file before using any WordPress functions and away you go. Below is an example of how to include the file:

<?php
require_once("wp-load.php");

your WordPress code here...

It’s as easy as that!

Note: If you’re adding your custom PHP file in your theme folder rather than on the root of your site, you need to make the ‘require_once’ relative to the path of the ‘wp-load.php’ file, as this file sits in the root of your site. Below is how you do so:

<?php
require_once("../../../wp-load.php");

your WordPress code here...

← Back to Blog