0

I have a function which uses Ajax calls:

function bs_reserve_gift()
{
    if (!wp_verify_nonce($_POST['_wpnonce'], 'reserve_gift')) {
        $response['status'] = 'error';
        $response['message'] = __('Something went wrong, please try again later!', 'bs');
        echo json_encode($response);
        exit();

    } else {
        update_post_meta($_POST['reserve_gift_id'], 'gift_status', 'reserved');
        $response['status'] = 'success';
        $response['gift_id'] = $_POST['reserve_gift_id'];
        $response['message'] = __('Thank you, the gift was reserved for you!', 'bs');
        echo json_encode($response);
        exit();

    }

}

add_action('wp_ajax_nopriv_reserve_gift', 'bs_reserve_gift');
add_action('wp_ajax_reserve_gift', 'bs_reserve_gift');

This works for logged in users, but for non logged users the nonce doesn't validate for some reason...

How can I solve this?

2

Use check_ajax_referer: https://codex.wordpress.org/Function_Reference/check_ajax_referer

//Check nonce
if ( !check_ajax_referer( 'nonce-action-name', '_wpnonce', false ) ){
    echo __('Ajax Security Check', 'yourtextdomain');
    die();
}
1
  • Thanks, this works, but I'm still curious why the wp_verify_nonce doesn't work... – user1049961 Apr 16 '15 at 21:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.