<?php
/**
* Lightweight frontend ajax alternative to admin-ajax.php
* Modified from admin-ajax.php @ v4.4.1
*
* @author Michael Niles <codepad@blindmikey.com>
* @version 1.0.0
*/
/** Executing AJAX process. */
define( 'DOING_AJAX', true );
/*
* Optionally get even more lightweight and require only
* what you need after wp-load.php
*
* https://core.trac.wordpress.org/browser/branches/3.4/wp-settings.php#L99
*/
// define('SHORTINIT', true);
/**
* Load WordPress Bootstrap
* assumes file is in theme root. Adjust as needed
*/
require_once( '../../../wp-load.php' );
// if SHORTINIT add your require_once()'s here
/** Allow for cross-domain requests (from the frontend). */
send_origin_headers();
/** Require an action parameter */
if ( empty( $_REQUEST['action'] ) )
die( '0' );
/** Setup headers */
@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
@header( 'X-Robots-Tag: noindex' );
/** Send a HTTP header to disable content type sniffing in browsers which support it. */
send_nosniff_header();
/** Set headers to prevent caching for browsers. */
nocache_headers();
/**
* Optionally allow specified actions
*/
/*
$approved_actions = array(
'action_one',
'action_two',
);
if( ! in_array( esc_attr( trim( $_REQUEST['action'] ) ), $approved_actions ) )
die( '0' );
*/
/** Register core Ajax calls. */
if ( is_user_logged_in() )
{
do_action( 'wp_ajax_' . $_REQUEST['action'] );
}
else
{
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}
/** Default status */
die( '0' );
Need front-end ajax capability for your wordpress site, but don't want the overhead? Here's a stripped down admin-ajax.php
7 Responses
The current setup assumes this file is placed in theme root I believe.
Also, when I register a new ajax call function in the functions.php file, how will it 'know' to make the call via this front-end ajax file instead of the admin-ajax.php file?
Example:
add_action('wp_ajax_my_ajax_function_name', 'my_ajax_function_name');
add_action('wp_ajax_nopriv_my_ajax_function_name', 'my_ajax_function_name');
I appreciate your help :)
Best,
Best,
Write a comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.