WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I got the following code which takes and image, uploads it to my server and sets it as a featured image.

How can i change it so it adds the image to the product gallery in Woocommerce? Maybe something like generating and attaching metadata?

function postmeta_img_update($postid, $img ) {
global $post;
require_once(ABSPATH . 'wp-includes/pluggable.php'); 
// If Custom Post Meta Field for a Image/Thumnail NOT Exists
if( !get_post_meta($postid, "skipimage", true) ): // if meta exists then skip

// Get File Extention
$ext = substr(strrchr($img,'.'),1);

// WordPress Upload Directory to Copy to (must be CHMOD to 777)
$uploads = wp_upload_dir();
$copydir = $uploads['path']."/";

// Code to Copy Image to WordPress Upload Directory (Server Must Support     file_get_content/fopen/fputs)
$data = file_get_contents($img);
$filetitle = strtolower(str_replace(array(' ', '-', '.', '(', ')', '!', '@', '#', '$', '%', '^', '&', '*', '_', '=', '+'), "-", get_the_title()));
$file = fopen($copydir . "$filetitle-$postid.$ext", "w+");
fputs($file, $data);

// Insert Image to WordPress Media Libarby
$filepath = $uploads['path']."/$filetitle-$post->ID.$ext";

$wp_filetype = wp_check_filetype(basename($filepath), null );
$attachment = array(
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => get_the_title(),
     'post_content' => 'Image for '.get_the_title(),
     'post_status' => 'inherit'

wp_insert_attachment( $attachment, $filepath, $postid);

// Get Attachment ID for Post
global $wpdb; $attachment_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_parent = '$postid' AND post_status = 'inherit' AND post_type='attachment' ORDER BY post_date DESC LIMIT 1");
// Attached Image as Featured Thumbnail in Post
update_post_meta($postid, "_thumbnail_id", $attachment_id);


share|improve this question
fyi, wp_insert_attachment returns the attachment ID, no need for the subsequent query for $attachment_id. does the woocommerce gallery not simply output all images attached to a post? I'm not aware that you have to do anything beyond attaching it. – Milo Oct 12 '13 at 18:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.