Skip to content

Instantly share code, notes, and snippets.

@danielbachhuber
Created June 28, 2012 21:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielbachhuber/3013900 to your computer and use it in GitHub Desktop.
Save danielbachhuber/3013900 to your computer and use it in GitHub Desktop.
Use the Rewrite API to interpret AJAX requests
<?php
add_action( 'init', function(){
add_rewrite_rule( '^ajax/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?','index.php?ajax=true&action=$matches[1]&type=$matches[2]&offset=$matches[3]&meta=$matches[4]','top' );
});
add_filter( 'query_vars', function( $query_vars ){
$query_vars[] = 'ajax';
$query_vars[] = 'action';
$query_vars[] = 'cat';
$query_vars[] = 'offset';
$query_vars[] = 'meta';
return $query_vars;
});
add_action( 'template_redirect', function() {
// Don't do anything unless this is an AJAX request
if ( !get_query_var( 'ajax' ) )
return;
$my_data = array(
'action' => sanitize_key( get_query_var( 'action' ) ),
'type' => sanitize_key( get_query_var( 'cat' ) ),
'offset' => intval( get_query_var( 'offset' ) ),
'meta' => sanitize_key( get_query_var( 'meta' ) ),
);
echo json_encode( $my_data );
die();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment