Created
September 8, 2013 20:16
-
-
Save PabloVallejo/6488040 to your computer and use it in GitHub Desktop.
Code example written for http://pablovallejo.me/debugging-wp-ajax/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment