Wordpress: Lightweight frontend-ajax alternative to admin-ajax.php

<?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

Where would you put this file? In /wp-content?
@Robert Pop You can put it anywhere, so long as the 'require_once(...' line on line 28 is correctly pointed to wp-load.php

The current setup assumes this file is placed in theme root I believe.
@Michael Niles Thanks for clarifying, Michael!

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 :)
@Robert Pop When you call wp_localize_script() to include the ajax_url, just point to your front-end ajax file instead of the native wordpress one.

Best,
@Michael Niles Thanks again for your help!
When you call wp_localize_script() to include the ajax_url, just point to your front-end ajax file instead of the native wordpress one.

Best,
@Michael Niles Can't delete mistaken comment?

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.