Code example written for http://pablovallejo.me/debugging-wp-ajax/
<?php
/**
* Function that will handle post insertion with data from
* POST request.
*
* <code>
*
* // Sample returned response
* ( object ) array( 'status'=> 200, 'post_id' => 10 );
*
* <code>
*
* Note: you should validate your data before creating a
* WordPress Post.
*/
function ajax_create_post() {
// Set post data up.
$data = array(
'post_title' => $_POST[ 'post_title' ]
, 'post_content' => $_POST[ 'post_content' ]
);
// Create a response object.
$response = ( object ) array(
'status' => 600
);
// Create a post.
$post_id = wp_insert_post( $data );
// Check whether the post was inserted.
if ( is_numeric( $post_id ) ) {
$response->status = 200;
$response->post_id = $post_id;
}
// Print response.
echo json_encode( $response );
die();
}
// Bind action "wp_ajax_ajax_create_post" to "ajax_create_post" function.
add_action( 'wp_ajax_ajax_create_post', 'ajax_create_post' );
// Set the _POST attributes you want to use.
$_POST = array(
'post_title' => 'My post title'
, 'post_content' => 'Sample post inserted via AJAX'
);
// Trigger action
do_action( 'wp_ajax_ajax_create_post' );