Hack the WordPress AJAX procedure…

Here I describe an unusual way to use AJAX inside WordPress, by usual "admin-ajax.php" URL.

Usually we run AJAX in WordPress with following code:

add_action('wp_ajax_mp_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');

function my_action() {
...
}

Then we fire it with GET query to "http://my_site.com/wp-admin/admin-ajax.php?action=my_action" or POST query to "http://my_site.com/wp-admin/admin-ajax.php" with parameter "action=my_action".

Today I got a problem with an API, which sends POST query with predefined parameter "action". I was creating a plugin, which needs interaction with WordPress, so solution had to be AJAX. But I would have two "action" parameters, server will ignore one...

Well, if I can not change API's "action", let me use it:

add_action('wp_ajax_the_legacy_action', 'my_action');
add_action('wp_ajax_nopriv_the_legacy_action', 'my_action');
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');

function my_action() {
...
}

Such way my function runs both with "the_legacy_action" and "my_action" as value of "action" parameter. Then just with a check which one was used I can find where it runs from. And it works.

Not a new idea, actually. I use it in my KC Last Active Time plugin. But second action there was second short code to my function, instead of "foreign" "action" parameter.

The only problem what I see is that some other plugin can use "the_legacy_action" too... But I see two options here: can check for existing WP action, or can create small "wick" script, to transform "action=the_legacy_action" to "legacyaction=the_legacy_action"... Well, will play with this if needs.

This entry was posted in Blog, Hacks and tagged , . Bookmark the permalink.

Leave a Reply