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

I want a script in my theme, ajax.php, which I want to load or access from other frontend pages using ajax.

In ajax.php I want access to core WP functions such as get_posts(), do_shortcode() etc. I.e. I need WordPress loaded on the script.

Traditionally I have setup a page in the admin and given it a custom template so then for my ajax requests I can send to www.site.com/ajax and the custom template handles the request. While this works fine I'm pretty sure this is not the most efficient, or safest way of handling ajax on WP frontend but not sure how to do it properly.


share|improve this question
up vote 5 down vote accepted

It is really not best practice to do it this way at all. In fact you don't need to create an ajax.php file unless you're just going to include it in your functions.php file. You need to read up on AJAX in WordPress. You would just add an action on 'wp_ajax_name_of_action' and just specify the action within the javascript ajax function.

Simple example from the WordPress codec:

add_action('admin_head', 'my_action_javascript');

function my_action_javascript() {
<script type="text/javascript" >
jQuery(document).ready(function($) {

var data = {
    action: 'my_action',
    whatever: 1234

// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
    alert('Got this from the server: ' + response);
add_action('wp_ajax_my_action', 'my_action_callback');

function my_action_callback() {
global $wpdb; // this is how you get access to the database

$whatever = intval( $_POST['whatever'] );

$whatever += 10;

    echo $whatever;

die(); // this is required to return a proper result
share|improve this answer

See the codex page on how to properly use AJAX in plugins. The same actions will work in a theme's functions.php as well.

Also see this blog post linked on the above codex page for more code samples.

share|improve this answer
Thanks for the links. It's the "admin-ajax" that's always put me off reading those properly for front end solutions.. – patnz Nov 3 '11 at 21:05

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.