ethon wiliams ethon wiliams - 1 year ago 100
PHP Question

How to upload post image and set as a future image from front end?

I want to upload image and set as a future image from front end.

I have used

set_post_thumbnail( $post_id , $attach_id);
but it can't work.

Anyone know more about it how to do this?

Answer Source

paste following code in your active theme’s functions.php file

 function insert_attachment($file_handler,$post_id,$setthumb='false')      {
    if (@$_FILES[$file_handler]['error'] !== 0){ return false;  }

    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attach_id = media_handle_upload( $file_handler, $post_id );
    set_post_thumbnail( $post_id , $attach_id);
    if ($setthumb)
     return $attach_id;

} ?>

for access it add below code in your custom template.

    if ($_FILES) {
    $i = 0;//this will count the posts
    foreach ($_FILES as $file => $array) {
    if ($i == 0) $set_feature = 1; //if $i ==0 then we are dealing with the first post
    else $set_feature = 0; //if $i!=0 we are not dealing with the first post
    $newupload = insert_attachment($file,$parentPostId, $set_feature);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download