jlittlejohn
8/26/2014 - 2:37 PM

WP: Enable Ajax in WordPress

WP: Enable Ajax in WordPress

<?php

// Put JavaScript into Template
function enable_ajax_functionality() {
  wp_localize_script( 'ajaxify', 'ajaxify_function', array('ajaxurl' => admin_url('admin-ajax.php')) );
}
add_action('template_redirect', 'enable_ajax_functionality');

// Add two actions to wp_ajax, where we get posts array back as json
function test_ajax() {
  header( "Content-Type: application/json");
  $posts_array = get_posts();
  echo json_encode($posts_array);
  die();
}
add_action("wp_ajax_nopriv_test_ajax", "test_ajax");
add_action("wp_ajax_test_ajax", "test_ajax");

?>