WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

My theme implements an AJAX action that returns some dynamic content and needs some functions from the Wordpress environment. How can I construct a URL for the AJAX call in the most elegant and robust way?

In particular, I see lots of themes and plugins directly linking to PHP files that are inside their directory tree, which in turn are totally different entry points from Wordpress's index.php, and then include this:

define('WP_USE_THEMES', false);

From an architecture perspective, this does not seem elegant to me (we create another entry point to the app), and it also breaks if I want to symlink the theme directory to some place else.

I think WordPress doesn't implement a full-fledged router as the ones from typical Web frameworks, but is there a way to create specific (not custom posts, for instance) frontend URLs?

share|improve this question
up vote 3 down vote accepted

Read AJAX in Plugins. Themes work the same way. So, you get an API, some gotchas inclusive. :)

Our tag is quite popular too; you may find some good solutions there.

share|improve this answer
I had stumbled upon this article, but was unsure whether this was what I was looking for. I will read it in more detail and post my findings -- thanks! – julien_c Mar 7 '12 at 19:25
It is what you're looking for. Despite the admin-ajax.php file name, it works everywhere (assuming everything is hooked in correctly). – chrisguitarguy Mar 7 '12 at 19:31
...and not hidden behind some if ( ! is_admin() ) conditional :P – kaiser Mar 7 '12 at 21:00
Finally got to try it, and it answers my needs perfectly. Only thing that was not obvious (at least to me) in the doc page is that you should actually replace my_action in the hook name itself (wp_ajax_my_action) by your own string. For the sake of completeness with respect to the question, is there a way to create custom frontend URLs? Should I create a "fake page" and add a specific template file? – julien_c Mar 15 '12 at 22:51
@julien_c Custom URLs aren’t so hard. I recommend A (Mostly) Complete Guide to the WordPress Rewrite API as a start. – toscho Mar 16 '12 at 4:07

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.