How to use Ajax In WordPress
Here is a simple tutorial to use Ajax in wordpress. Here we are taking an example to fetch the titles of all posts belong to the same post type as per the user’s choice.User need to put the exact post type name. Now, we will go through the topic step by step :
STEP 1 : Add a form in your template where you want to show click button.
<form action="" method="post"> <label>Write post type : </label> <input type="text" name="post_type" id="post_type" value=""/> <input type="button" value="Show Post Titles" onclick="myajaxfunction()"/> </form>
STEP 2 : Add ajax “myajaxfunction()” function in the same file :
<script type="text/javascript"> function myajaxfunction() { $.ajax({ //ajax request url: ajaxurl, data: { 'action':'my_request', 'post_type' : $('#post_type').val() // value of text box having id "post_type" }, success:function(data) { //result $(".showdiv").html(data); //showdiv is the class of the div where we want to show the results }, error: function(errorThrown){ console.log(errorThrown); } }); } </script>
STEP 3 : Add the below mentioned code to the function.php :
function my_request() { if ( isset($_REQUEST) ) { // $_REQUEST is having all the data sent using ajax $post_type= $_REQUEST['post_type']; $sunil_args = array( 'post_type' => $post_type); $sunil_query = new WP_Query( $sunil_args ); if ( $sunil_query->have_posts() ) { while ( $sunil_query->have_posts() ) { $sunil_query->the_post(); ?><p><?php echo the_title();?></p><?php } } } die(); } add_action( 'wp_ajax_my_request', 'my_request' ); //for logged in users only
Step 4 : Prepare a div to show the results :
<div class="showdiv"></div>
After the above mentioned steps we can easily use ajax in wordpress. One thing we need to keep in mind that this will work for all the logged in users.
For non-logged in users we need to add another line in function.php file :
add_action( 'wp_ajax_nopriv_my_request', 'my_request' ); //for non-logged in users
In this way you can prepare a separate functions for logged in and non-logged in users.
If you face an issue like “ajaxurl is not defined” after implementation of ajax, then in this case you need to define “ajaxurl” for front-end. Just check here : Solution to ReferenceError: ajaxurl is not defined , you will get solution to this issue.
THANK YOU VERY MUCH!!!