Wp Ajax – WordPress Hook to Handle Ajax Request

wp_ajax is not a hook or callback itself, rather it is a prefix for hooks. Those hooks become available while making an ajax call. When a browser or web-client sends a request with an action query parameter to the http://example.com/wp-admin/admin-ajax.php file, a hook becomes available to use, which uses wp_ajax_ as its prefix.

Brief

A request to wp-admin/admin-ajax.php?action=contact-us will make the wp_ajax_contact-us action hook available. Here you can see the action is fired by appending the requested action query parameter value contact-us to wp_ajax_. Programmatically, it is 'wp_ajax_' . $_REQUEST['action']. By attaching a function to this hook, responses are sent back to the browser or the ajax call.


Table of content

  1. How to use action hook generated by an ajax request
  2. Why request to wp-admin/admin-ajax.php file
  3. What is wp_ajax_nopriv
  4. How to use the hook for both Logged & Not Logged in members
  5. What is WordPress ajaxurl
  6. Adding ajaxurl to Front pages
  7. Example – Using Ajax in WordPress

How to use the ajax request generated action hook ?

Any request to the admin-ajax.php file brings a hook name, and that hook is used to send a response. A function or class method is required to handle the response, and the response handler is attached using the add_action() function.
Example:add_action( 'wp_ajax_contact-us', 'contact_us_requested_by_ajax' );.
Explanation: Here contact_us_requested_by_ajax is a function you use to do some processing and/or send some output for the request. You can replace the function name contact_us_requested_by_ajax with something else of course.


Why do I or WP send requests to the wp-admin/admin-ajax.php file ?

Because the wp-admin/admin-ajax.php file was built to handle ajax requests, we can call it the ajax request resolver. This file handles the initial processing and enables a catchable hook after loading all of the WordPress core files, active plugin files and the theme’s functions.php file (this makes WP functions available for you to use within the hook). So, all you have to do is use the hook in your theme’s functions.php file or inside a plugin file, and you won’t have to worry about WordPress file/library inclusion.


What is wp_ajax_nopriv ?

The wp_ajax_ prefix isn’t used to create the hook name when the user is not logged in, wp_ajax_nopriv_ is used instead. wp_ajax_nopriv_ does the same thing as the wp_ajax_ prefix, except it only fires when the user is not logged in. So for a not logged-in user the hook name is – 'wp_ajax_nopriv_' . $_REQUEST['action'], and for a logged-in user it is 'wp_ajax_' . $_REQUEST['action'].


How to use the hook for both logged-in/not-logged-in User/visitor ?

Simple. Use both the wp_ajax_ and wp_ajax_nopriv_ prefixed hooks with your function. Example –

add_action( 'wp_ajax_contact-us', 'contact_us_requested' );
add_action( 'wp_ajax_nopriv_contact-us', 'contact_us_requested' );

Note: Both hooks will never be fired at once for a single request, as WordPress itself does the user/non-user validation and triggers the appropriate hook. So your function will be called only once, not twice. — for further reference, you can explore the admin-ajax.php file inside the wp-admin directory.


What is WordPress ajaxurl

ajaxurl is a common JavaScript variable which holds the ajax request handler file uri. In WordPress it is the url of the yoursite.com/wp-admin/admin-ajax.php file. WordPress automatically includes this variable on every WP Admin page, but not on the front pages (post/page/category/author/search/tag etc). Developers define this JS variable themselves or create a different one, but the purpose is the same – assigning the ajax request handler url to a JS variable. For example, Contact Form 7 passes the url in its own settings variable instead of relying on a global.


How to add the ajaxurl variable to WordPress site Front pages ?

If you are enqueuing any JavaScript at the front, this variable can be added using the wp_localize_script function.

function w4dev_enqueue_scripts() {
    wp_register_script( 'myjs', 'https://example.com/script.js' );

    wp_localize_script(
        'myjs',
        'myjs',
        array(
            'ajaxurl' => admin_url( 'admin-ajax.php' )
        )
    );

    wp_enqueue_script( 'myjs' );
}
add_action( 'wp_enqueue_scripts', 'w4dev_enqueue_scripts' );

However, if you are not loading any js file, this can also be added by using the code below in your theme/plugin file. In this code, the custom function w4dev_ajaxurl_cdata_to_front hooks into wp_head and prints js which defines the ajaxurl for global use.

function w4dev_ajaxurl_cdata_to_front(){
    ?>
    <script type="text/javascript"> //<![CDATA[
        ajaxurl = '<?php echo admin_url( 'admin-ajax.php'); ?>';
    //]]> </script>
    <?php
}
add_action( 'wp_head', 'w4dev_ajaxurl_cdata_to_front', 1 );

Simplest Example – Using Ajax in WordPress

Goal: Display the Site Description upon clicking an anchor.
Brief: First, we will add a link with a unique HTML/CSS id attribute ( within a content area ex: sidebar, content, footer etc or hardcoded in theme template files ) and use a jQuery onclick function to send a request to ajaxurl and display the returned value using a JavaScript alert.

Anchor to be placed:

<a id="view_site_description" href="javascript:void(0);">View Our Site Description</a>

Next, add the JavaScript code using the wp_footer hook.

function add_js_to_wp_footer(){ ?>
    <script type="text/javascript">
    jQuery('#view_site_description').click(function(){
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {"action": "view_site_description"},
            success: function(data){alert(data);}
        });
        return false;
    });
    </script>
<?php }
add_action( 'wp_footer', 'add_js_to_wp_footer' );

Add this to your theme’s functions.php or a plugin file.

Explanation: In the above code, we have used the jQuery OnClick event. Whenever an element having the id view_site_description is clicked, jQuery will send an HTTP POST request to the ajaxurl ( wp-admin/admin-ajax.php file ) with a query string action=view_site_description, and the return value will be shown as a JavaScript alert.

You read earlier that a request to the wp-admin/admin-ajax.php file creates a WP action hook, and using that hook we can produce anything we want. A request to the admin-ajax.php file will make the wp_ajax_view_site_description or wp_ajax_nopriv_view_site_description hook available if the action parameter value is set to view_site_description.

Next create a function to process the request and display the site description.

function view_site_description(){
    echo get_bloginfo( 'description', 'display' );
    exit;
}
add_action( 'wp_ajax_view_site_description', 'view_site_description' );
add_action( 'wp_ajax_nopriv_view_site_description', 'view_site_description' );

Add this to your theme’s functions.php or a plugin file.

Now if everything is OK and well placed, clicking the link will alert you with your site description. Put the last three blocks of code in your theme, and try it yourself.

Notice: If your theme does not load jQuery, then you will need to add a few lines of code to load it. The code below will load jQuery, you can paste it in your theme’s functions.php file.

function w4dev_enqueue_jquery(){
    wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'w4dev_enqueue_jquery');

That’s it, I hope this writing helped you understand using Ajax in your WordPress site & wp_ajax. These days WordPress also offers the REST API for building custom endpoints, which is the more modern route, but admin-ajax.php still works fine and is used by many plugins.


Related Reference

Leave a Reply

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