Issue with front-end ajax, getting a 302 redirect when accessing wp-admin/admin-ajax.php

2018-04-13 10:00:17

I want to use wp ajax for frontend logged in user but showing error of 302 Found and call home page.

it is working fine for admin users and non logged in users.

here is network log screenshot:

i have used both ajax function like below:

add_action('wp_ajax_add_sale', 'add_sale');

add_action('wp_ajax_nopriv_add_sale', 'add_sale');

add_sale() below:

function add_sale() {

die("hello");

$salevehicleid = $_POST['salevehicleid'];

$saleuserhidid = $_POST['saleuserhidid'];

$saleusername = $_POST['saleusername'];

$saleuseremail = $_POST['saleuseremail'];

$saledate = date('Y-m-d H:i:s');

$letsaleplaced = true;

$response = array();

// $saleuserhidid = (int)0;

// if(is_user_logged_in()){

// $user_id = get_current_user_id();

// if ($user_id == 0) {

// $saleuserhidid = (int)0;

// } else {

// $saleuserhidid = (int)$user_id;

// }

// }else{

// $saleuserhidid = (int

  • Below function works for me by adding !defined('DOING_AJAX') in condition.

    function custom_blockusers_init() {

    if ( is_admin() && !defined('DOING_AJAX') && (

    current_user_can('usercrp') || current_user_can('userpcp') ||

    current_user_can('subscriber') || current_user_can('contributor') ||

    current_user_can('editor'))) {

    session_destroy();

    wp_logout();

    wp_redirect( home_url() );

    exit;

    }

    }

    add_action( 'init', 'custom_blockusers_init' );

    2018-04-13 11:55:27