Skip to content

Instantly share code, notes, and snippets.

@seamusleahy
Created September 11, 2012 17:08
Show Gist options
  • Save seamusleahy/3699884 to your computer and use it in GitHub Desktop.
Save seamusleahy/3699884 to your computer and use it in GitHub Desktop.
Simply add AJAX callbacks to your WordPress Theme
<?php
/**
* 1. Add this to your theme's functions.php file.
* 2. Create an 'ajax' folder in your theme directory.
* 3. Create a PHP file to handle the AJAX call in the ajax folder.
* 4. From Javascript, make an AJAX call using jQuery:
* 5. $.get( window.themeSettings.ajaxUrl, {action: window.themeSettings.themeAjaxAction, template: 'YOUR TEMPLATE NAME (MINUS THE .php EXTENSION)'}, function( data ) { } );
*/
/**
* A generic AJAX handler for the theme
*/
function themename_themeajax_handler() {
$template = isset($_REQUEST['template']) ? $_REQUEST['template'] : '';
if( !empty($template) ) {
locate_template( array('ajax/'.$template.'.php'), true );
die();
}
}
add_action('wp_ajax_nopriv_themeajax', 'themename_themeajax_handler');
add_action('wp_ajax_themeajax', 'themename_themeajax_handler');
/**
* Set the content-type for the header
*
* @param $type string - the short reference for the type
*
* Accepted types: json, javascript, rss, text, xml, atom, css, html
*/
function themename_themeajax_set_type( $type ) {
$types = array(
'json' => 'application/json',
'javascript' => 'text/javascript',
'rss' => 'application/rss+xml; charset=ISO-8859-1',
'text' => 'text/plain',
'xml' => 'text/xml',
'atom' => 'application/atom+xml',
'css' => 'text/css',
'html' => 'text/html'
);
if( isset($types[$type]) ) {
header( 'Content-type: '.$types[$type] );
}
}
function themename_themeajax_print_settings() {
echo '<script>';
echo 'window.themeSettings = ';
echo json_encode(array(
'ajaxUrl' => get_bloginfo('wpurl').'/wp-admin/admin-ajax.php',
'themeAjaxAction' => 'themeajax'
));
echo '</script>';
}
add_action( 'wp_print_scripts', 'themename_themeajax_print_settings' );
@rinatkhaziev
Copy link

Couple of issues: all ajax requests should be properly nonced,
it's better to use wp_localize_script() for what you're doing in themename_themeajax_print_settings()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment