How to create a specific frontend URL (not a Page) from a theme or plugin?

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?

1 Answer
1

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

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

Leave a Comment