Exciting News! Flipper Code is now WePlugins! Same commitment to excellence, brand new identity.

How to use check_ajax_referer action in WordPress

Sandeep Kumar Mishra
Sandeep Kumar Mishra
May 18, 2023
5 minutes read

Let’s talk about the check_ajax_referer action in WordPress. This hook is your go-to when you want to ensure that an Ajax request is validated. It’s like a security gatekeeper for your Ajax calls. And trust me, as an Indian developer, getting this right can save you a lot of headaches down the line!

To use the check_ajax_referer action, you first need to register it using add_action. You can place this code in your theme’s functions.php file or, better yet, in a custom WordPress Plugin. At WePlugins, we always prefer creating custom WordPress Plugins to keep things safe during theme updates.

Below, you’ll find some live examples to help you get started.

Example 1: Basic Usage of check_ajax_referer

Here’s a simple example of how you can use this hook in your WordPress site.

    function weplugins_execute_on_check_ajax_referer_event($action, $result){
       // Execute code when this action occurs. Use the parameters to implement custom functionality.
    }
    // add the action
    add_action( "check_ajax_referer", "weplugins_execute_on_check_ajax_referer_event" , 10, 2);
    

Example 2: Removing a Hook Callback

If you need to remove a registered hook, use remove_action like this.

    remove_action( "check_ajax_referer", "weplugins_execute_on_check_ajax_referer_event", 10, 2 );
    

Ensure you provide the same callback function name, priority, and number of arguments when removing.

Example 3: Hook with Custom Functionality

In this example, we’ll extend the hook’s functionality to meet specific website requirements.

    function weplugins_custom_ajax_functionality($action, $result){
       // Custom code for specific website needs.
    }
    add_action( "check_ajax_referer", "weplugins_custom_ajax_functionality" , 20, 2);
    

When using check_ajax_referer, remember it takes two parameters:

  • $action: The Ajax nonce action as a string.
  • $result: Indicates the validity of the nonce. False if invalid, 1 if valid and recent, 2 if valid but older.

Access Premium WordPress Plugins

Contact Us

If you need any help or customization, feel free to contact us. We’re here to assist you with your WordPress needs!

Sandeep Kumar Mishra

Sandeep Kumar Mishra

Sandeep Kumar Mishra writes about WordPress and Artificial Intelligence, offering tips and guides to help you master your website and stay updated with the latest tech trends.

Explore the latest in WordPress

Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.