Today I’ve been setting up WordPress as the News section of a website which loads its pages via AJAX requests whenever possible, but falls back on normal HTTP requests when the AJAX loads are not possible.
The when the AJAX requests are initiated from Javascript, /outputxml/ is added to the end of the URL. This gets translated, with some mod_rewrite magic, to a $_GET
parameter called output. /outputxhtml is also possible but since that’s the default it doesn’t get used very much.
After, (mostly), building the WordPress theme I started testing, and as I expected I ran into some problems when /outputxml/ was added to the end of the WordPress URLs. I got 404 errors, which makes total sense. I thought I could get around this by simply doing a little extra mod_rewrite magic, however, it seems there’s not way to simply replace /outputxml somewhere in a url with an empty string using mod_rewrite alone. After some time, I stumbled upon an underdocumented WordPress function: WP_Rewrite::add_endpoint
and its friend, add_rewrite_endpoint
. These functions make it so that WordPress recognizes /category/post-name/trackback, and /category/post-name/outputxml. Excellent!
I just had to create a plugin, make sure that WordPress wouldn’t kill my $_GET[‘output’] variable, add 1 line to my .htaccess and I was good to go.
References:
- codex.wordpress.org/Query_Overview – explains the steps WordPress goes through when responding to a request
- codex.wordpress.org/User:DavidHouse/WP_Rewrite_API#add_rewrite_endpoint.28.29 – the most human add_rewrite_endpoint documentation
And this is what my plugin looks like, (for educational purposes only. I am not distributing it):
function fourRS_outputxml_activate() {
global $wp_rewrite;
add_rewrite_endpoint('outputxml',array(EP_PERMALINK, EP_PAGES));
add_rewrite_endpoint('outputxml',EP_ALL);
$wp_rewrite->flush_rules();
}
register_activation_hook( __FILE__, 'fourRS_outputxml_activate');
function fourRS_outputxml_deactivate() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
register_deactivation_hook( __FILE__, 'fourRS_outputxml_deactivate');
/* Makes it so WP doesn't eat my nice $_GET variable */
function fourRS_parameter_queryvars( $qvars )
{
$qvars[] = 'output';
return $qvars;
}
add_filter('query_vars', 'fourRS_parameter_queryvars' );
Edit (August 25, 2009): Changed the attrbutes in the add_rewrite_endpoint()
function.