Wp Ajax – WordPress Hook to Handle Ajax Request
wp_ajax is not a hook or callback, rather it is just a prefix of hooks or callbacks. Those callbacks are usually available while making ajax call. When a browser or web-client request with an action
query parameter to http://example.com/wp–admin/admin–ajax.php file, a hook becomes available to use. Which use wp_ajax_
as prefix.
Brief
A request to wp-admin/admin-ajax.php?action=contact-us will make wp_ajax_contact-us
action hook available. Here you can see the Action is fired by appending wp_ajax_
to the requested action
query parameter value contact-us. Programmatically, it is 'wp_ajax_' . $_REQUEST['action']
. Attaching a function with this hook, responses are sent to browser or to the ajax call.
Table of content
- How to use action hook generated by an ajax request
- Why request to wp-admin/admin-ajax.php file
- What is wp_ajax_nopriv
- How to use the hook for both Logged & Not Logged in members
- What is WordPress ajaxurl
- Adding ajaxurl to Front pages
- Example – Using Ajax in WordPress
How to use the ajax request generated action hook ?
Any request to admin-ajax.php file bring a hook name, and that hook is used to send some response. A function or class method is required to handle the response though. And response handler is attached using 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 sending some output for the request. You can replace the function name from contact_us_requested_by_ajax
to something else ofcourse.
Why do i or WP send request to wp-admin/admin-ajax.php
file ?
Because, wp-admin/admin-ajax.php file was built to handle ajax requests, we can call it as ajax request resolver. This file handles initial processing and enable a chatchable hook after loading all of WordPress core files, active plugin files and themes functions.php file (this makes WP functions available for you to use within the hook). So, all you have to do is to use the hook in your themes functions.php file or inside a plugin file and won’t have to worry about WordPress file/library inclusion.
What is wp_ajax_nopriv
?
wp_ajax_
prefix isn’t used to create the hook name if user is not logged in, therefore wp_ajax_nopriv_
is used. wp_ajax_nopriv_
does the same thing as wp_ajax_
prefix does, unless it only fires when user is not logged in. So for not logged-in user the hook name is – 'wp_ajax_nopriv_' . $_REQUEST['action']
, and for 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 wp_ajax_
and wp_ajax_nopriv_
prefixed hook with your function. Example –
add_action( 'wp_ajax_contact-us', 'contact_us_requested' );
add_action( 'wp_ajax_nopriv_contact-us', 'contact_us_requested' );
Note: Not both of the hook will be fired at once for a single request, as WordPress itself do user/non-user validation and triggers the appropriate hook. So your function will be called only once not twice. — for further assistance, you could explore admin-ajax.php
file inside wp-admin
directory for reference.
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 yoursite.com/wp-admin/admin-ajax.php
file. WordPress automatically include this variable on every page on WP Admin pages, but not on the front pages (post/page/category/author/search/tag etc). Developer define this JS variable or create a different variable, but purpose is the same – assigning ajax request handler url on a JS variable. Example: Contact Form 7 add their own variable name as wpcf_ajax_url
.
How to add ajaxurl
variable name to WordPress site Front pages ?
If you are enqueuing any javaScript at front, this variable can be added using 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 below codes on your theme/plugin file. In this code, custom function w4dev_ajaxurl_cdata_to_front
hook’s to wp_head
and print 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 Site Description upon clicking on an Anchor.
Brief: First, we will add a link with a unique HTML/CSS id attribute ( within content are ex: sidebar, content, footer etc or hardcode in theme template files ) and use jQuery onclick function to send a request to ajaxurl and display the return value using Javascript alert.
Anchor to be placed:
<a id="view_site_description" href="javascript:void(0);">View Our Site Description</a>
Next, Adding the JavaScript codes using 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 themes functions.php or a plugin file
Explanation: In the above code, we have used jQuery OnClick event. Whenever, an element having id view_site_description
is clicked, jQuery will Send a 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 an JavaScript alert.
You read earlier that, a request to wp-admin/admin-ajax.php file creates a WP Action hook, and using the hook we can produce anything we want. A request to the admin-ajax.php
file will make available wp_ajax_view_site_description
or wp_ajax_nopriv_view_site_description
hook if action parameter value is set to view_site_description
Next create a function to process the request and display 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 themes functions.php or a plugin file.
Now if everything is OK and well placed, clicking on the link will alert you with your site description. Put the last three block of code on your theme, and try it yourself.
Notice: If your theme does not loads jQuery, then you will need to add few line of code to load jQuery. Below code will load jQuery, you can paste this code on 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, hope this writing helped you to understand Using Ajax in your WordPress site & wp_ajax.