Skip to content

Instantly share code, notes, and snippets.

@mcascardi
Created October 31, 2018 17:33
Show Gist options
  • Save mcascardi/31400683de0a1edc2d32ab337c020909 to your computer and use it in GitHub Desktop.
Save mcascardi/31400683de0a1edc2d32ab337c020909 to your computer and use it in GitHub Desktop.
Fast AJAX handler for wp
<?php
/**
* Hello, this is a minimal ajax handler for WP.
* Based off of: https://coderwall.com/p/of7y2q/faster-ajax-for-wordpress which didn't work for me out of the box.
* Note: replace tld with your own prefix.
* Handles get and post type requests.
* Assumes you put this file in the root directory of your theme folder.
*/
$_tld_ajax = [];
function get_sanitized_action() {
return filter_var(
((!empty($_GET['action'])) ? $_GET['action'] : $_POST['action']),
FILTER_SANITIZE_STRING
);
}
//mimic the actuall admin-ajax
define('DOING_AJAX', true);
if (!isset($_POST['action']) && !isset($_GET['action'])) {
die('-1');
}
$_tld_ajax['action'] = get_sanitized_action();
//A bit of security
$_tld_ajax['allowed_actions'] = [
// Only allow actions we know about
'blog_archive'
];
if(!in_array($_tld_ajax['action'], $_tld_ajax['allowed_actions'])){
die('-1');
}
//make sure you update this line
//to the relative location of the wp-load.php
require_once('../../../wp-load.php');
//Typical headers
header('Content-Type: text/html');
send_nosniff_header();
//Disable caching
header('Cache-Control: no-cache');
header('Pragma: no-cache');
if(is_user_logged_in()) {
do_action("tld_ajax_{$_tld_ajax['action']}");
} else {
do_action("tld_ajax_nopriv_{$_tld_ajax['action']}");
}
// EOF
@mcascardi
Copy link
Author

To use this, just define your ajax handler functions as normal, and then hook them to the actions you see below in the do_action() calls.

eg:

function my_ajax_function() {
  ...
}

add_action('tld_ajax_my_handler', 'my_ajax_function');
add_action('tld_ajax_nopriv_my_handler', 'my_ajax_function');

// somewhere in javascript:
$.ajax('/wp-content/themes/{theme_name}/ajax.php', {'action' => 'my_action'});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment