How I upload, save and set a featured image from my frontend?

Question

I have a form on my site.

This the user register one missing person.
I created a custom post type missing person, custom taxonomies, and custom fields.
All this input’s save as well in wp.

But I don’t know submit an image and save this image as featured image.

$my_post = array(
                 'post_title' => $_POST['title'],
                 'post_date' => $_SESSION['cal_startdate'],
                 'post_content' => $_POST['myContent'],
                 'post_status' => 'draft',
                 'post_type' => 'pessoa_desaparecida',
              );

$post_id = wp_insert_post($my_post);


$uploaddir = wp_upload_dir();
$file = $_FILES["test"]["name"];
$uploadfile = $uploaddir['path'] . '/' . basename( $file );

move_uploaded_file( $file , $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 );
update_post_meta($post_id,'_thumbnail_id',$attach_id);

set_post_thumbnail( $post_id, $thumbnail_id );

but not works

My Form in frontend is:

<form action="/homolog/cadastro" method="post" enctype="multipart/form-data">
 <input type="text"  name="title" />
 <input type="file" size="20"  name="test" />
</form>

PRINT:

enter image description here

enter image description here

0
, , , Arie 9 years 2014-07-20T19:35:59-05:00 0 Answers 82 views 0

Leave an answer

Browse
Browse