ethon wiliams ethon wiliams - 1 month ago 9
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

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

<?php 
 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)
       update_post_meta($post_id,'_thumbnail_id',$attach_id);
     return $attach_id;

} ?>

for access it add below code in your custom template.

  <?php
    if ($_FILES) {
    array_reverse($_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);
    $i++;
    }
    }
     ?>