Search code examples
phpwordpresscustomizationcustom-wordpress-pages

Image is showing in wordpress localhost uploads folder but not updating in wordpress media library (wp dashboard))


I'm trying to upload image using wp custom template in child theme but when i upload any image. It appears in "E:\Xamp\htdocs\website\wp-content\uploads\2019\10" but not uploaded to wp dashboard media library.

I'M NOT ALLOWED TO USE ANY PLUGIN FOR THIS TASK.

$post_id = wp_insert_post($my_post);

if(isset($_FILES['file']['name'])){
    if(! function_exists('wp_handle_upload')){
        require_once(ABSPATH.'wp-admin/includes/file.php');
    }
    $uploadfile = $_FILES['file'];
    print_r($uploadfile);
    $upload_overrides = array('test_form' => false );

    $moveupload = wp_handle_upload($uploadfile,$upload_overrides);
    if($moveupload && ! isset($moveupload['error'])){
        echo "</Pre";
        wp_update_attachment_metadata( $post_id, $moveupload);
        print_r($moveupload);
        echo "Post/>";
    }else{
        echo $moveupload['error'];
    }
}

Solution

  • Can try out another piece of code here:
    --------------------------
    $upload_overrides = array( "test_form" => false );
    
    $uploaded_file = wp_handle_upload ($file, $upload_overrides);
    
    if( isset( $uploaded_file ["file"] )) {
        $file_name_and_location = $uploaded_file ["file"];
        $file_title_for_media_library = $title;
    
        $attachment = array(
            "post_mime_type" => $uploaded_file_type,
            "post_title" => addslashes( $file_title_for_media_library ),
            "post_content" => "",
            "post_status" => "inherit"
        );
    
        if( ! is_null( $post )) {
            if ( ! is_numeric( $post )) {
                $post = $post->ID;
            } // if ()
    
            $attachment ['post_parent'] = $post;
        } // if ()
    
        $id = wp_insert_attachment( $attachment, $file_name_and_location );
    
        require_once( ABSPATH."wp-admin/includes/image.php" );
    
        $attach_data = wp_generate_attachment_metadata( $id, $file_name_and_location );
        wp_update_attachment_metadata( $id, $attach_data );
    } // if ()