Skip to content

Instantly share code, notes, and snippets.

@iainmcampbell
Last active August 29, 2015 14:13
Show Gist options
  • Save iainmcampbell/cedb806a23629738c698 to your computer and use it in GitHub Desktop.
Save iainmcampbell/cedb806a23629738c698 to your computer and use it in GitHub Desktop.
Wordpress Ajax
<?php
add_action('wp_ajax_myajaxfunctionname', 'ajax_myajaxfunctionname');
add_action('wp_ajax_nopriv_myajaxfunctionname', 'ajax_myajaxfunctionname');
function ajax_myajaxfunctionname(){
$var = $_POST['var'];
if( ! isset($var) ) die(1);
// try to supply from cache
$page_from_cache = get_option( "cache_id{$var}", 0 );
if($page_from_cache){
die($page_from_cache);
}
ob_start(); // start collecting for cache
// echo stuff, wp_query, whatever
// save to cache
update_option( "cache_id{$var}", ob_get_flush() );
die();
}
?>
<?php
add_action('wp_ajax_myajaxfunctionname', 'ajax_myajaxfunctionname');
add_action('wp_ajax_nopriv_myajaxfunctionname', 'ajax_myajaxfunctionname');
function ajax_myajaxfunctionname(){
$var = $_POST['var'];
if( ! isset($var) ) exit(1);
// echo stuff, wp_query, whatever you want
exit;
}
?>
$.post(
ajax_params.ajax_url,
{
action: 'myajaxfunctionname',
var: 'asdf' // vars here are accessible using $_POST
},
function( responseHTML ){
$('body').append( responseHTML )
}
)
<?php
// piggyback AJAX url via register_script
wp_register_script( 'theme-ajax-js', get_bloginfo('template_url').'/js/main.js', array('jquery'), '', true );
wp_localize_script( 'theme-ajax-js', 'ajax_params', array( 'ajax_url' => admin_url('admin-ajax.php') ) );
wp_enqueue_script( 'theme-ajax-js' );
?>
<?php
if( ! function_exists('va_invalidate_year_archive_ajax_cache') ) :
function va_invalidate_year_archive_ajax_cache( $post_id ){
delete_option('cache_id{$var}');
}
endif;
add_action('save_post', 'va_invalidate_year_archive_ajax_cache');
add_action('save_post_customposttype', 'va_invalidate_year_archive_ajax_cache');
?>
@iainmcampbell
Copy link
Author

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