How to add an AJAX function / URL to WordPress

Put this function in your theme’s functions.php (or even better, in an ajax.php file in the theme that is require’d in):

/* The function ajax_read_more() will be called when the following URL is requested
 * from WordPress:
 *
 * http://www.yoursite.com/wp-admin/admin-ajax.php?action=read_more&limit=5
 */
function ajax_read_more() {
    // Take in a few input parameters from $_GET or $_POST (depending on how you're passing the values) about
    // what data to retrieve and display.
    $num_limit = (int) $_POST['limit'];
    $str_category_name = filter_var($_POST['category_name'], FILTER_SANITIZE_STRING);
  
    // Call some built-in WordPress functions just to demonstrate that we can.
    $user_id = get_current_user_id();
  
    // Now let's return some JSON data to whatever called this URL (we can return HTML, XML or whatever else too,
    // just make sure to set the appropriate Content-Type header).
    $arr_sample_data = array('key' => 'value');
    echo json_encode($arr_sample_data);
    exit; // You must use exit to end an AJAX function in WordPress, or it'll append a 0 to the output.
}
add_action( 'wp_ajax_read_more', 'ajax_read_more' ); // This action exposes the AJAX action "read_more" to logged-in WordPress users.
add_action( 'wp_ajax_nopriv_read_more', 'ajax_read_more' ); // This action exposes the AJAX action "read_more" to anonymous (not logged in) WordPress users.

Then all you need to do is write a jQuery or even just a regular HTML form that submits a request to your new AJAX URL:

jQuery.ajax({
    type: 'get',
    url: '/wp-admin/admin-ajax.php?action=read_more&limit=5',
    dataType: 'json'
})
.done( function( response ) {
    console.log(response);
});

One last thing – visit your WordPress site’s Permalinks page in order to rebuild the list of URLs WordPress will respond to. This will make your new URL (for the AJAX function) active.

Leave a Reply

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