// Triggered for users that are logged in.
add_action( 'wp_ajax_create_new_post', 'wp_ajax_create_new_post_handler' );
// Triggered for users that are not logged in.
add_action( 'wp_ajax_nopriv_create_new_post', 'wp_ajax_create_new_post_handler' );
function wp_ajax_create_new_post_handler() {
// This is unfiltered, not validated and non-sanitized data.
// Prepare everything and trust no input
// For example: Insert or update a post
$post_id = wp_insert_post( array(
'post_title' => $data['title'],
// If everything worked out, pass in any data required for your JS callback.
// In this example, wp_insert_post() returned the ID of the newly created post
// This adds an `exit`/`die` by itself, so no need to call it.
if ( ! is_wp_error( $post_id ) ) {
wp_send_json_success( array(
// If something went wrong, the last part will be bypassed and this part can execute:
wp_send_json_error( array(
add_action( 'wp_enqueue_scripts', 'register_localize_and_enqueue_a_script' );
function register_localize_and_enqueue_a_script() {
get_template_directory_uri().'/js/functions.js',
filemtime( get_template_directory().'/js/functions.js' ),
// Send in localized data to the script.
'ajax_url' => admin_url( 'admin-ajax.php' ),
wp_enqueue_script( 'my-script' );