Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lukecarbis
Created October 28, 2014 19:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lukecarbis/6180629d7936d4b0a7eb to your computer and use it in GitHub Desktop.
Save lukecarbis/6180629d7936d4b0a7eb to your computer and use it in GitHub Desktop.
WordPress AJAX Frontend Execution
<?php
/**
* WordPress AJAX Frontend Execution.
*
* Using WP Ajax should not be used from the frontend because response
* from `admin-ajax.php` are not cached (including `nocache_headers()`).
* Instead, you should add a query var, and then do the `template_include`
* routine to select a template that returns JSON.
*
* A side benefit here is that it makes your site more RESTful.
*/
function wp_ajax_query_vars( $vars ){
$vars[] = 'wp_ajax_action';
return $vars;
}
add_filter( 'query_vars', 'wp_ajax_query_vars' );
public function wp_ajax_callback( $template ) {
$wp_ajax_action = get_query_var( 'wp_ajax_action' );
if ( $wp_ajax_action ) {
// Executing AJAX process
define( 'DOING_AJAX', true );
if ( ! has_action( 'wp_ajax_' . $wp_ajax_action ) && ! has_action( 'wp_ajax_nopriv_' . $wp_ajax_action ) ) {
// No ajax action found
status_header( 404 );
wp_send_json_error();
}
if ( is_user_logged_in() ) {
/**
* Fires authenticated AJAX actions for logged-in users.
*
* The dynamic portion of the hook name, $wp_ajax_action,
* refers to the name of the AJAX action callback being fired.
*
* @since 4.1.0
*/
do_action( 'wp_ajax_' . $wp_ajax_action );
} else {
/**
* Fires non-authenticated AJAX actions for logged-out users.
*
* The dynamic portion of the hook name, $wp_ajax_action,
* refers to the name of the AJAX action callback being fired.
*
* @since 4.1.0
*/
do_action( 'wp_ajax_nopriv_' . $wp_ajax_action );
}
}
return $template
}
add_filter( 'template_include', array( $this, 'wp_ajax_callback' ) );
/**
* Example usage.
*/
function example_frontend_ajax_enqueue() {
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_script.js', __FILE__ ) );
$ajax_url = add_query_arg( array( 'wp_ajax_action', 'my_action' ), get_home_url() );
// in JavaScript, object properties are accessed as window.ajaxurl
wp_localize_script( 'ajax-script', 'window', array( 'ajaxurl' => $ajax_url ) );
}
add_action( 'enqueue_scripts', 'example_frontend_ajax_enqueue' );
function example_frontend_ajax_callback() {
/*
* Do stuff
*/
wp_send_json_success();
}
add_action( 'wp_ajax_my_action', 'example_frontend_ajax_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'example_frontend_ajax_callback' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment