Right way to insert attachment in WordPress, insert attachment using wp_insert_attachment function, simple tutorial and example code.

How To Insert Attachment In WordPress

Using wp_insert_attachment() function and some functions, we will insert attachment in WordPress.

Insert Attachment Function

Copy function code and paste it in your functions.php file:

function WPTime_insert_attachment(){
    // Function by Qassim Hassan, wp-time.com

    require_once( ABSPATH . 'wp-admin/includes/image.php' ); // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.

    $wp_upload_dir = wp_upload_dir();

    $dir_name = substr($wp_upload_dir['subdir'], 1); // you can change this to custom folder, for example: $dir_name = "my-images"; now go to "uploads" folder and create new folder "my-images"

    $filename = $dir_name.'/photo.jpg'; // firstly: don't forget to upload "photo.jpg" to your last sub dir or to custom folder

    $filetype = wp_check_filetype( basename( $filename ), null ); // get file mime type

    $attachment = array(
      'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), // image link
       'post_mime_type' => $filetype['type'], // will be display file mime type
       'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ), // will be display file name, you can change it to custom name or random numbers rand()
       'post_content' => '', // optional
       'post_status' => 'inherit', // optional

    $parent_post_id = 0; // enter post ID if you want to display this image as parent, you can leave it 0 this is optional

    $attachment_id = wp_insert_attachment($attachment, $filename, $parent_post_id);

    $get_size = getimagesize($wp_upload_dir['baseurl']."/".$filename); // get image width and height

    $data = array('ID' => wp_generate_attachment_metadata( $attachment_id, $filename ), 'width' => $get_size[0], 'height' => $get_size[1]);

    wp_update_attachment_metadata( $attachment_id, $data );

Now upload your file “photo.jpg” in the last subdirectory, for example my last subdirectory is “2016/06”, look to this image:

last subdirectory

Now call function in functions.php file, like this:

WPTime_insert_attachment(); // insert attachment!

The result:

insert attachment in wordpress



If you want to upload image in custom folder, go to “wp-content” > “uploads” and create a new folder, for example my custom folder name is “custom”:

custom folder

Now in “custom” folder, upload your image, for example upload “man.jpg“, and replace this lines from function code:

// replace this:

$dir_name = substr($wp_upload_dir['subdir'], 1);

// to this:

$dir_name = "custom"; // your custom folder name, you can change the folder name to any name

// and replace this:

$filename = $dir_name.'/photo.jpg';

// to this:

$filename = $dir_name.'/man.jpg'; // your file name

Now call function! the result: