Use WordPress functions in a custom PHP file outside WordPress
I was working to change one of my custom option group settings option of WordPress via a cron job. I did this work in a custom PHP file that is non-WordPress. So I had to find a way where I can use WordPress functions in a non-WordPress PHP script.
Luckily I was able to find the perfect way which helped me to use WordPress functions in my custom PHP script that is outside of my WordPress installed. So I thought why not share this with you what I learned and what I did so that you can also learn new thing.
The trick I find is amazing. When I find this trick for the first time, it surprises me. I hope, you are also going to feel like me when you will also learn using WP functions in custom PHP code.
Anyone may have to face the situation like me. You may also in the situation like me where you have to use WordPress functions in non-Wordpress PHP script.
So this post is going to tell you how to use WordPress functions in a custom PHP file outside WordPress.
Now let’s start…
Suppose, you have a PHP file in the root where WordPress has installed. Now you want to use all the WordPress functions in that PHP file.
After some research, I found that most of the useful and important WordPress files that contain most of the useful functions are already included in “wp-load.php” file which is in the root of WordPress.
So all you need to do is to include the “wp-load.php” file using the PHP require_once statement before you start coding for WordPress in your custom PHP file and start using WordPress functions:
<?php require_once("wp-load.php"); // All your WordPress code will be here...
Now you can test by using those functions that you used for WordPress inside plugins or theme’s functions.php.
Now suppose, your PHP file is inside a directory or inside multiple levels of directories. In this case, you have to set the relative path of the “wp-load.php” file just like you can see below:
<?php require_once("../../wp-load.php"); // Use your WordPress functions here...
Now do whatever you like using the WordPress functions in your custom PHP file.
- Add a submenu page under WordPress Settings menu
- Nexmo WooCommerce SMS Alert Notification WordPress Plugin