Adding AJAX function to your WordPress like Loading more posts
button will be more user friendly. Following are the simple way to call AJAX in a WordPress plugin.
HTML
When this button is clicked, it sends AJAX request to our defined URL, which is admin-ajax.php
in this case.
<form> <button class="ajax_button" name="submit" data-author="TLTemplates">Post AJAX</button> </form>
Plugin’s PHP file
We use wp_ajax_nopriv_[action_name]
and wp_ajax_nopriv_[action_name]
actions to define a function which handles AJAX request. The former is for logged-in users while the later is for guests.
In the plugin file, we need to enqueue JavaScript file and use wp_localize_script
to register ajax URL.
function myplugin_scripts() { wp_enqueue_script('myplugin-js', plugin_dir_url(__DIR__). '/my-plugin.js', array('jquery'), time() ); wp_localize_script( 'myplugin-js', 'ajax_obj', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )) ); } add_action('wp_ajax_nopriv_myaction', 'myaction_callback'); add_action('wp_ajax_myaction', 'myaction_callback'); function myaction_callback(){ $author = $_POST['author']; echo 'Author: '.$author; wp_die(); }
my-plugin.js
jQuery(document).ready(function(){ jQuery('.ajax_button').on('click', function(){ var data = { action: 'myaction', author: jQuery(this).attr('data-author') }; jQuery.post( ajax_obj.ajaxurl, data, function( response ) { console.log( response ); }); }); });
Here is the result we will see in the console after clicking on Post AJAX button.
