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?

1 Answer 1


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.

  • 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, 2012 at 19:25
  • 1
    It is what you're looking for. Despite the admin-ajax.php file name, it works everywhere (assuming everything is hooked in correctly). Mar 7, 2012 at 19:31
  • ...and not hidden behind some if ( ! is_admin() ) conditional :P
    – kaiser
    Mar 7, 2012 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, 2012 at 22:51
  • 1
    @julien_c Custom URLs aren’t so hard. I recommend A (Mostly) Complete Guide to the WordPress Rewrite API as a start.
    – fuxia
    Mar 16, 2012 at 4:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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