Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom ajax handler for Wordpress. Using admin-ajax.php, as is usually recommended, is very slow and does not allow the use of plugin shortcodes. Using a custom ajax handler like this bypasses that. http://wordpress.stackexchange.com/questions/170808/the-content-shows-shortcode-instead-of-parsing-it
<?php
/*
WORDPRESS SPECIFIC AJAX HANDLER (because admin-ajax.php does not render plugin shortcodes).
by alexandre@pixeline.be
credits: Raz Ohad https://coderwall.com/p/of7y2q/faster-ajax-for-wordpress
*/
//mimic the actual admin-ajax
define('DOING_AJAX', true);
if (!isset( $_REQUEST['action']))
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');
$action = esc_attr(trim($_REQUEST['action']));
// Declare all actions that you will use this ajax handler for, as an added security measure.
$allowed_actions = array(
'dothis_dothat'
);
// Change DUMMY_ to something unique to your project.
if(in_array($action, $allowed_actions)) {
if(is_user_logged_in())
do_action('DUMMY_'.$action);
else
do_action('DUMMY_nopriv_'.$action);
} else {
die('-1');
}
<?php
/*
Inside your Theme's functions.php, you can now use it, via the allowed actions you specified.
*/
add_action("DUMMY_dothis_dothat", "a_function_name");
add_action("DUMMY_nopriv_dothis_dothat", "a_function_name_for_loggedin_users_only");
function a_function_name(){
echo "hello World";
exit();
}
function a_function_name_for_loggedin_users_only(){
echo "hello User";
exit();
}
<?php
/*
In any template, address that url for ajax requests like this:
*/
$link = get_bloginfo('template_directory').'/ajax-handler-wp.php?action=dothis_dothat&post_id='.get_the_ID();
?>
<a class="js-ajax-link" href="<?php the_permalink();?>" data-href="<?php echo $link ?>">hello who?</a>
@efoula

This comment has been minimized.

Copy link

commented Aug 9, 2018

Hi,

I am getting an 403 error while trying to access "ajax-handler-wp.php", even I am trying to access it directly through the web browser, it should show -1 instead of 403 Nginx error, by the way that happened after I upgraded the php version to 7

@alekskravchenko

This comment has been minimized.

Copy link

commented Aug 6, 2019

Hi,

I am getting an 403 error while trying to access "ajax-handler-wp.php", even I am trying to access it directly through the web browser, it should show -1 instead of 403 Nginx error, by the way that happened after I upgraded the php version to 7
@efoula do you fix this error ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.