I am trying to insert post from frontend form i have different fields and i also want to upload an image. But the problem is that all othere data store except image so here is my code
if( 'POST' == $_SERVER['REQUEST_METHOD' ] && !empty( $_POST['action' ] ) && $_POST['action' ] == "new_post") {
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Do some minor form validation to make sure there is content
if (isset ($_POST['post_title' ])) {
$title = $_POST['post_title' ];
} else {
echo 'Please enter the wine name' ;
}
if ($_POST['description' ] != '' ) {
$description = $_POST['description' ];
} else {
echo 'Please enter some notes' ;
}
$tags = $_POST['post_tags' ];
$post_link = $_POST['post_link' ];
// ADD THE FORM INPUT TO $new_post ARRAY
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => array($_POST['cat' ]), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'draft' , // Choose: publish, preview, future, draft, etc.
'post_type' => 'post' , //'post',page' or use a custom post type if you want to
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
//KEEPS OUR COMMA SEPARATED TAGS AS INDIVIDUAL
wp_set_post_tags($pid, $_POST['post_tags' ]);
//REDIRECT TO THE NEW POST ON SAVE
//$link = get_permalink( $pid );
//wp_redirect( $link );
//ADD OUR CUSTOM FIELDS
add_post_meta($pid, 'post_link' , $post_link, true);
//INSERT OUR MEDIA ATTACHMENTS
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = wp_insert_attachment($file,$pid);
// $newupload returns the attachment id of the file that
// was just uploaded. Do whatever you want with that now.
}
} // END THE IF STATEMENT FOR FILES
} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM
//POST THE POST YO
do_action('wp_insert_post' , 'wp_insert_post' );
Now please guide me and correct my code where i missing some thing. I have to upload image. Just modifiy this code. Thanks
wp_insert_attachmentdoesn't upload files, it inserts an attachment post for a file that's already been uploaded. I suggest you start by searching for examples ofmedia_handle_upload. – Milo Mar 12 at 5:49