Call any Wordpress PHP function via AJAX


Staff member
It's very difficult for me to learn the basics of AJAX since I was managed to find only complicated examples. In fact, I want to do an apparently simple thing, but I wasn't able to find any easy solution. There are numerous instructions how to use AJAX to check various forms, etc. But there is few data how this technology work in WordPress.

The official instruction was useless to me as well:
<a href="" rel="nofollow noreferrer"></a>

<em>What exactly I need?</em>

For example, I have some function in functions.php. Let it be a just simple string:


function do_echo() {

echo "Hello";


Now, I want to create a button inside my post and call do_echo() using AJAX.

&lt;button class="my_button" type="button" role="button"&gt;Click Me&lt;/button&gt;

So, the first and foremost thing I want to do is just push on the button and get "Hello, world!" displayed.

Of course, in fact, I need to execute the more complicated function. But, first of all, I need to do these simple things.

I realize that I need to do something like this using jQuery

url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, 
or html)',
data: {param1: 'value1'},
.done(function() {
.fail(function() {
.always(function() {

I understand that I need to do something like this in PHP

add_action('wp_ajax_(action)', 'my_action_callback');
add_action('wp_ajax_nopriv_(action)', 'my_action_callback');

But I can't understand what exact steps I need to do to attach these things to WordPress.

Can anyone assist me with the <strong>simple</strong> instruction how to call any PHP function from functions.php in <strong>WordPress</strong> using AJAX when the button was clicked?

Thank you in advance.