WordPress: How to use Ajax at front side without using admin-ajax.php
August 26, 2010 | In: ajax, javascript, Wordpress
Mostly all wordpress developers write the code to create widgets in admin side. and he use following code:
var ajaxurl ='<?php echo admin_url('admin-ajax.php');?>'; var data = { action: 'action_function_name' }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php jQuery.post(ajaxurl, data, function(response) { alert(response); }); |
But when he wants to use Ajax at front side without login in Admin side area. then admin-ajax.php file will not run because it is made for only admin. so here I am providing solution:
Just create a new file front-ajax.php and put below code inside the file:
<?php /** * WordPress AJAX Process Execution for Front side. * Author : Naveenos * Url : http://naveenos.com */ define('DOING_AJAX', true); define('WP_ADMIN', true); require_once('../wp-load.php'); if ( ! isset( $_REQUEST['action'] ) ) die('-1'); require_once('./includes/admin.php'); @header('Content-Type: text/html; charset=' . get_option('blog_charset')); send_nosniff_header(); do_action('admin_init'); if ( ! is_user_logged_in() ) { if ( !empty( $_REQUEST['action'] ) ) do_action( 'wp_ajax_' . $_REQUEST['action'] ); die('-2'); } if ( isset( $_GET['action'] ) ) : switch ( $action = $_GET['action'] ) : default : do_action( 'wp_ajax_' . $_GET['action'] ); die('0'); break; endswitch; endif; $id = isset($_POST['id'])? (int) $_POST['id'] : 0; switch ( $action = $_POST['action'] ) : default : do_action( 'wp_ajax_' . $_POST['action'] ); die('0'); break; endswitch; ?> |
And use front-ajax.php rather than admin-ajax.php in your code. This code is running well at my side.