Use plugin function outside WordPress file

If you are intent on calling into WordPress functionality from outside of the usual WP workflow, you can put the following two lines in your code:

define("WP_USE_THEMES", false);
require_once("../../../wp-blog-header.php");

Of course, the above assumes I’m calling this from within a root theme or plugin folder (the ../ indicates reverse folder traversal). It looks as though you’ve already included wp-blog-header.php, and the define is an indication to WordPress not to invoke certain functionality related to normal page/post queries. For an example of how WordPress functionality can be implemented in a disparate PHP codebase, I would suggest you look at this Laravel+Wordpress post or similar attempts to utilize WordPress functionality from outside of WordPress itself. If you need the functionality WordPress offers (including that of its activated plugins) this might be the best solution.

Otherwise, depending on your scenario, invoking WordPress code as Ajax, as suggested by other users, may be the appropriate route to go. In particular, if you wanted to implement a simple CRUD API, such as a RESTful operation, this would be the suggested route. This is the route I would personally recommend if all you are interested in doing is moving data from points A and B.

Your code may have failed because you didn’t define the WP_USE_THEMES flag properly; under normal circumstances, functionality offered by plugins isn’t available until after a certain point (probably the init action, based on http://codex.wordpress.org/Plugin_API/Action_Reference), and trying to call plugin functionality before that action has occurred may result in what you describe.

Leave a Comment