0

can someone give me please a code for image upload ? i try many but no one works , this is what i have :

    $post = array(
              'comment_status' => $comment_status,
              'ping_status'    => 'open',
              'post_author'    => $user_id,
              'post_content'   => '',
              'post_status'    => $status,
              'post_title'     => $title,
              'post_type'      => 'post',
             );  
            $post_id = wp_insert_post($post);



    if($_FILES['image_imagepost']['error'] == 0) {

            function insert_attachment($file_handler,$post_id,$setthumb='false'){

// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __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 = ( $file_handler, $post_id );

if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
            }

I try to make a post and upload a image,the post is ok but the image didin't upload on media. Thanks.

4
  • Please add your solution as an answer and accept it ;-) Commented Mar 10, 2016 at 15:17
  • i did it but i can't accept it, why?
    – I.Alex
    Commented Mar 10, 2016 at 15:19
  • O crap yes, there is a stupid 48 hour restriction. You will only be ably able to accept your own answer in 2 days ;-) Commented Mar 10, 2016 at 15:22
  • Ok , i will do that if i rembember :D
    – I.Alex
    Commented Mar 10, 2016 at 15:30

1 Answer 1

0

well i look and i look and finally i found this work that work for me.

    $upload = wp_upload_bits( $_FILES['image']['name'], null, file_get_contents( $_FILES['image']['tmp_name'] ) );

    $wp_filetype = wp_check_filetype( basename( $upload['file'] ), null );

    $wp_upload_dir = wp_upload_dir();

    $attachment = array(
        'guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path( $upload['file'] ),
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', basename( $upload['file'] )),
        'post_content' => '',
        'post_status' => 'inherit'
    );

    $attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );

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

    $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    update_post_meta( $post_id, '_thumbnail_id', $attach_id );

    wp_redirect( site_url() . '/thank-you/' );

    die();
}

from here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.