How to integrate a custom PHP file with WordPress

You can use WordPress functionality in a custom PHP script. A few lines of code on top of the PHP fie will do the trick. Consequently the script will be able to use WP global object variables like $wpdb.

Why do you need WordPress functionality outside WordPress?

ANSWER: Probably you need to manipulate some WordPress data for a 3rd party application. Or maybe you need to integrate your WP website into a different website on your server ( a forum, a simple PHP website etc).

Where can I add my PHP file?

First of all, the PHP file can be added anywhere on your server. Therefore it can be on root, separate folder, inside /wp-content/ folder, inside /wp-content/themes/ folder etc. You need to understand that adding the script anywhere in your WP folders will not make your script integrated with WordPress.

The code to integrate WP with the PHP script

So here’s the code will allow you to use all WordPress functions and global object variables in a standalone PHP script:

<?php
$absPath = dirname(__FILE__);
$realPath = realpath($absPath . '/./');
$fPath = explode("wp-content",$realPath);
define('WP_USE_THEMES', false);
require(''.$fPath[0].'/wp-blog-header.php');
?>

The above special code, added on top of the file, determines the path to the script. Then it loads wp-blog-header.php which it is actually responsible to add all WP functionality to the script.
Finally please let us know how is this working for you. So if you have any questions we would be glad to help.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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