[wp-hackers] ajax and $wpdb
Otto
otto at ottodestruct.com
Thu Jul 30 13:28:28 UTC 2009
The short of it is that there is never really a need for your plugin
to directly include the WordPress code, via wp-load or wp-config or
anything else.
The cases where people try to do this are multiple, but end up being
resolvable through different means.
Case 1: AJAX.
You have your plugin calling some file in the plugin via script tags
or ajax or something, and you think "hey, since I need access to the
DB, this ajax file I'm making needs to include wp-load". False, your
plugin needs to hook into the wp_ajax_* actions and you need to make
the page make a call to admin_url('admin-ajax.php'); with a proper
?action=whatever parameter.
Case 2: You need to get some kind of output from a separate call to a
file in your plugin.
You have your plugin calling some other file in the plugin, which
produces some special kind of output (image, text, whatever), and it
needs access to WordPress functions and such, so you want to include
wp-load. Again, false. Your plugin needs to hook into
template_redirect and add a query variable so it can recognize when
it's being called. Example:
add_filter('query_vars', 'add_my_var');
function add_my_var($public_query_vars) {
$public_query_vars[] = 'some_unique_identifier';
return $public_query_vars;
}
add_action('template_redirect', 'my_var_output');
function my_var_output() {
$myvalue=get_query_var('some_unique_identifier');
if ($myvalue) {
// do whatever output you like here
// you can even use $myvalue to see what the request is for
exit; // this stops WordPress entirely
}
}
Any call to the main WP url with ?=some_unique_identifier=whatever
will now cause your output to run and WordPress to stop execution
afterwards. So you can override the output with anything you like.
Want an image output? Throw out a header() call to set the mime type
and output the image data. And since you're in a plugin context, you
have WP functions available to you.
So, never include wp-load (or blog-header or config, etc) from a
plugin, even a separate file. It's simply not necessary.
-Otto
More information about the wp-hackers
mailing list