Last Updated on 2022-03-10 by Clay
Today I want to record a bit of strange requirement: how to use WordPress core function in external PHP file. I think some people may need it in future, because I see the same problem on stackoverflow (https://stackoverflow.com/questions/29791763/use-get-option-in-external-php-file).
Why to do that? It is because I write a external php file, and it can interact with HTML to present an interface; in the process, I need to call the WordPress core methods get_option() and update_option() to complete the function of my page.
The external php file it does not under my plugin or theme directory. If you put it in a theme folder or developing a plugin, the default is to use all WordPress libraries.
So how do we call WordPress core function from external files?
Solution
Taking get_option()
and update_option()
as an example, we need to read the file wp-load.php through the require_once()
function, so that the system knows where to read the two functions and what to do operate.
The wp-load.php file is usually under the WordPress directory. For the general plugin development folder, the following command should be used to read the file:
require_once('../../../wp-load.php');
If the external PHP file is in the same folder as wp-load.php, use:
require_once('../../../wp-load.php');
Simply put, all you have to enter is the path to wp-load.php.
References
Read More
- [WordPress] Use PHP Program To Edit A Specific Page Content
- [Solved] Parse error: syntax error, unexpected ''lists_page'' (T_CONSTANT_ENCAPSED_STRING), expecting ')' in /var/www/html/wp-content/plugins/reserve-course/reserve-course.php on line 54
- [Solved] Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'change page_content' not found or invalid function name in