I’m trying to “Import” the WordPress core into an own script to use the functionality such as wp_query etc. I’ve created an script in a subdirectory (own framework) and want to extend it by wordpress, but everytime the script throws an error:
Fatal error: Call to a member function add_rewrite_tag() on a non-object in …/wordpress/wp-includes/taxonomy.php on line 333
such as (when I remove the add_action( ‘init’, ‘create_initial_taxonomies’, 0 )):
Fatal error: Call to a member function add_rewrite_tag() on a non-object in …/wordpress/wp-includes/post.php on line 1006
The non-object is the $wp_rewrite-object. I’ve echo’ed something and figured out that first $wp_rewrite is valid and at the next call not. I’ve changed nothing at the WP core files.
I try to include the core by calling:
require_once(BASE_PATH . 'wp-load.php');
Has anybody some ideas for me?
thanks
Short answer, do this:
Long answer, it’s a subtle gotcha around importing scripts with PHP.
If you define a local variable, outside of all functions, then it can be retrieved inside a function using ‘global’. If you have a local variable inside a function, it cannot be retrieved later using global, unless it is defined as being global there and then.
The script ‘wp-settings.php’ is where the issue lies. It is included via your call to include ‘wp-load.php’.
The variables defined there are not stated as being global; instead this is presumed because the script is always run outside of any functions, and so are automatically global. i.e.
Because you are importing the script within a function, they now become local variables. You are essentially doing:
So the fix is to define them as global yourself before importing the script. Now $wp_query, and the others defined as global, are correctly found.
The easiest way to access everything wordpress has programmed in is to use the following:
Using the above code you’ll get all functions you would normally get using a template with in WordPress. I’ve tried all the other methods listed above and this one is by far the best.
I had the same error. I wanted to get some articles along with permalinks. This helped:
I also found this useful in another case:
http://www.stormyfrog.com/using-wpdb-outside-wordpress/