How To Use Ajax Request In WordPress Theme

Hello WordPress Developer

In this example tutorial i will show you how to use ajax in wordpress theme. Sometimes we need to use Ajax request in our WordPress theme for showing data in frontend or save data into database.

In this tutorial i will show you a demo tutorial where we see how we can setup ajax request in our wordpress theme. In this example tutorial i will create a simple button and when we click this button, then a number of post will be showed without page refresh.

We will also see how to fetch data from database in wordpress using ajax. I also add shortcode to show this button. I also use jquery with wordpress ajax request. So let's test our wordpress ajax frontend tutorial.

functions.php

add_shortcode( 'ajax_btn', 'my_shortcode' );

 

After doing that we need to create this my_shortcode callback function to use ajax in wordpress. Let's create it.

 

Now we need to create my_ajax_action function. So paste this below code to your functions.php file.

 

Now in the final step we need to create our add action hook for wp ajax request. So see the below code to understand.

add_action('wp_ajax_my_ajax_action','my_ajax_function');
add_action('wp_ajax_nopriv_my_ajax_action','my_ajax_function');

 

Read also : How to Create an Advanced Theme Options Page in WordPress

 

Now just we need to paste this shortcode [ajax_btn] in our page or just have to echo this shortcode to show the ajax request button. Hope it can help you. Just give a try and check it.

 

#wordpress #ajax #custom-query