For creating new post from front-end, you can use template and paste below code into functions.php file.
/*
* Localize Ajax Script
*/
function js_enqueue_scripts() {
wp_register_script("my-ajax-handle", get_stylesheet_directory_uri() . "/assets/js/ajax.js", array('jquery'));
wp_enqueue_script("my-ajax-handle");
//the_ajax_script will use to print admin-ajax url in custom ajax.js
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action("wp_enqueue_scripts", "js_enqueue_scripts");
//In functions.php
function the_ajax_hook() {
global $wpdb;
$post_title = $_POST['post_title'];
$post_content = $_POST['post_content'];
$post_title = $_POST['post_title'];
$file = $_FILES["image"]["name"];
if ('POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST['action']) && $_POST['action'] == "the_ajax_hook") {
if (!(is_array($_POST) && is_array($_FILES) && defined('DOING_AJAX') && DOING_AJAX)) {
return;
}
if (!function_exists('wp_handle_upload')) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
}
$new_post = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'draft',
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . basename($file);
move_uploaded_file($_FILES["image"]["tmp_name"], $uploadfile);
$filename = basename($uploadfile);
$wp_filetype = wp_check_filetype(basename($filename), null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'menu_order' => $_i + 1000
);
$attach_id = wp_insert_attachment($attachment, $uploadfile);
set_post_thumbnail($post_id, $attach_id);
die();
}
}
add_action('wp_ajax_the_ajax_hook', 'the_ajax_hook');
add_action('wp_ajax_nopriv_the_ajax_hook', 'the_ajax_hook');
//Put below form on template file
<form class="wrap" id="post_form" action = "" method = "POST" enctype="multipart/form-data">
<div class="form-group">
<label>Title</label>
<input type="text" name="post_title">
</div>
<div class="form-group">
<label>Content</label>
<input type="text" name="post_content">
</div>
<div class="form-group">
<label>Featured Images</label>
<input type="file" name="image" id="fileToUpload">
<input type="hidden" name="action" value="the_ajax_hook">
<input type="submit" value="Upload Image" name="submit">
</div>
</form>
// Place this script in ajax.js file
jQuery("#post_form").on('submit', function (event) {
event.preventDefault();
var data = new FormData(this);
data.append("action", "the_ajax_hook");
jQuery.post({
url: the_ajax_script.ajaxurl,
data: data,
contentType: false,
cache: false,
processData: false,
success: function (response) {
alert('Inserted');
$('form')[0].reset();
}
});
});
