Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

// INCLUDE WORDPRESS STUFF
define('WP_USE_THEMES', false);
include_once('../../../wp-load.php');

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
add comment

1 Answer 1

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
1  
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
1  
@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
show 1 more comment

Your Answer

 
discard

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.