Handling AJAX Requests

In WordPress, when handling AJAX requests, you can use two different types of action hooks:

  1. wp_ajax_{action} → For logged-in users.
  2. wp_ajax_nopriv_{action} → For non-logged-in users.

Why Use wp_ajax_nopriv?

You use wp_ajax_nopriv_{action} when you want to allow unauthenticated (non-logged-in) users to make AJAX requests. By default, WordPress restricts AJAX calls to logged-in users unless explicitly allowed for non-logged-in users.

Example Scenario

If you have an AJAX-based feature like:

  • A public contact form submission.
  • Adding products to the cart (if not using WooCommerce’s built-in AJAX).
  • Fetching live search results.
  • Voting in a poll.

Since these actions should work for all visitors (including those not logged in), you must use wp_ajax_nopriv_{action}.

Example Code:

Here’s how you define an AJAX request that works for both logged-in and non-logged-in users:

add_action('wp_ajax_my_custom_action', 'my_custom_ajax_function'); // For logged-in users
add_action('wp_ajax_nopriv_my_custom_action', 'my_custom_ajax_function'); // For non-logged-in users

function my_custom_ajax_function() {
    // Process the request
    $response = array('message' => 'Hello from AJAX!');
    wp_send_json_success($response);
}

AJAX Call in JavaScript:

jQuery(document).ready(function($) {
    $.ajax({
        url: ajaxurl, // WordPress provides this global variable
        type: 'POST',
        data: {
            action: 'my_custom_action'
        },
        success: function(response) {
            console.log(response.data.message);
        }
    });
});

When to Use Only wp_ajax_{action}?

If you want to restrict the AJAX call only to logged-in users (e.g., fetching user dashboard data), then you don’t need wp_ajax_nopriv_{action}.

Leave a Reply

Your email address will not be published. Required fields are marked *