Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of how to cache fronted ajax requests in WordPress. This will allow you to use ajax and page caching like varnish or redis. Where ajax requests would normally not be cached using the built in wp_ajax_action method.
<?php
add_filter( 'rewrite_rules_array', 'cache_frontend_ajax_rules' );
/**
* Rewrite rules filter to add rules for front end ajax calls
*
* @param array $rewrite_rules
*
* @return array
*/
function cache_frontend_ajax_rules( $rewrite_rules ) {
$ajax_rules = array(
'ajax/([^/]+?)/([^/]+?)/?$' => 'index.php?ajax_action=$matches[1]&ajax_data=$matches[2]'
);
return array_merge( $ajax_rules, $rewrite_rules );
}
add_action( 'init', 'cache_frontend_ajax_query_vars' );
/**
* Add query_vars for the ajax_action and ajax_data
*/
function cache_frontend_ajax_query_vars() {
global $wp;
$wp->add_query_var( 'ajax_data' );
$wp->add_query_var( 'ajax_action' );
}
add_action( 'template_redirect', 'cache_frontend_ajax_template_redirect' );
/**
* Gets ajax query_vars from url and calls correct ajax function
* replacement for add_action, wp_ajax_function_name
*/
function cache_frontend_ajax_template_redirect() {
$ajax_data = get_query_var( 'ajax_data' );
$ajax_function = get_query_var( 'ajax_action' );
$whitelist = array(
'wds_after_post_content',
'wds_featured_posts',
);
if ( ! empty( $ajax_function ) && in_array( $ajax_function, $white_list, true ) ) {
if ( ! empty( $ajax_data ) ) {
call_user_func( $ajax_function, $ajax_data );
}
exit;
}
}
/**
* Example wp_ajax_ function that gets passed the $post_id from the rewritten url
*
* @param int $post_id
*
* @return void
*/
function wds_after_post_content( $post_id ) {
$post = get_post( $post_id );
$related = wds_get_related_posts( $post );
wp_send_json_success( array( 'data' => $related ) );
}
/**
*
* Example javascript file contents
*
* (function($) {
* var ajaxurl = 'http://somesite.com';
*
* $(document).ready(function() {
* var post_id = $('.some_div' ).attr( 'id' );
* $.ajax({
* 'Type': 'GET',
* 'url': ajaxurl + '/wds_after_post_content/' + post_id + '/',
* success.function( response ) {
* $('.some_div').html( '<p>' + response.data + '</p>' );
* }
* )};
* });
* )}(jQuery);
*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment