Insert Post using Ajax

What says the error log? Is that the complete content of form-process.php? When it is so, then the problem might be, that the function wp_insert_post() is not defined, because the WordPress core was not loaded.

Therefore WordPress has an AJAX-API. Here’s an example on how to use that API on server side:

add_action( 'admin_ajax_your_form_action', 'wpse_126886_ajax_handler' );

function wpse_126886_ajax_handler() {

    // maybe check some permissions here, depending on your app
    if ( ! current_user_can( 'edit_posts' ) )
        exit;

    $post_data = array();
    //handle your form data here by accessing $_POST

    $new_post_ID = wp_insert_post( $post_data );

    // send some information back to the javascipt handler
    $response = array(
        'status' => '200',
        'message' => 'OK',
        'new_post_ID' => $new_post_ID
    );

    // normally, the script expects a json respone
    header( 'Content-Type: application/json; charset=utf-8' );
    echo json_encode( $response );

    exit; // important
}

The your_form_action slug is the »trigger« of your callback. You have to append this slug to your request parameter named action. To keep up with the .serialize() I suggest to pass this slug as a hidden input in your formular:

<input type="hidden" name="action" value="your_form_slug" />

Finally, you have to use the wp-admin/admin-ajax.php URL for your AJAX request:

$.ajax({
    type: "POST",
    url: "http://www.mysite.co.uk/wp-admin/admin-ajax.php",
    data: dataString,
    error: function(jqXHR, textStatus, errorThrown){                                        
        console.error("The following error occured: " + textStatus, errorThrown);                                                       
    },
    success: function(data) {                                       
        console.log("Hooray, it worked!");                                                                  
    }                              
});

Leave a Comment