How to use AJAX to call a function in WordPress

Published on July 12th, 2016

Photo by Rubén Santander on Unsplash

This might be old stuff for many people out there and I know that most things can be accomplished with the amazing WP API, still I think it’s good to have a simple example of using AJAX to call a WordPress function in one post. Here we go!


You want to request some data from WordPress (e.g. the previous post ID), through an AJAX call.

How to do this:

The way I solved this was to add a global variable in the header, so that the WordPress AJAX URL is exposed.
Then I added a function in my theme’s function.php file, which would do the actual work.
Finally, in my JavaScript file it’s just a matter of calling my function with AJAX. I can then use the result to do what I need.


In header.php

var ajaxurl = "' . admin_url('admin-ajax.php') . '";

In function.php

function get_prev_ajax_handler() {
  global $wpdb; // this is how you get access to the database
  $post_id = intval( $_POST['id'] ); // get the id value which has been posted
  global $post; // Get a global post reference
  $post = get_post( $post_id ); // Get the post object for the specified post
  echo get_previous_post()->ID; // Echo the previous post ID
  wp_die(); // close the connection

add_action('wp_ajax_get_prev', 'get_prev_ajax_handler'); // add action for logged users
add_action( 'wp_ajax_nopriv_get_prev', 'get_prev_ajax_handler' ); // add action for unlogged users

In script.js

function getPrevPostId(id){
  var prevPostId;        
  $.post( ajaxUrl, {           // POST request
      action: "get_prev",      // references to the function get_prev_ajax_handler() specified in functions.php 
      id: id                   // data
    }, function(prevPostId) {  // callback function using returned data
      console.log(prevPostId)  // do what thou wilt