Insert woocommerce products programmatically with featured image and gallery
I'm inserting WooCommerce products programmatically to the database, but I'm having trouble inserting and linking first image as featured image and multiple images for gallery assigned respectively to each product from multiple URLs, Would you have any idea how to do it?
?php
if(!empty($girls))
{
$ops = array_map('str_getcsv', file(get_option('siteurl') . '/wp-content/uploads/2022/02/'. $girls));
$myres = array_map('array_filter', $ops);
$ops2 = array_filter($myres);
$items = array();
foreach($ops2 as $username) {
$items[] = $username;
}
foreach ($items as $it) {
$title = array_key_exists(2, $it) ? $it[2] : null;
$description = array_key_exists(3, $it) ? $it[3] : null;
// Multiple images in each key
$img = array_key_exists(4, $it) ? $it[4] : null;
$secimg = explode(';', $img);
$category = array_key_exists(5, $it) ? $it[5] : null;
$price = array_key_exists(8, $it) ? $it[8] : null;
$stock = array_key_exists(6, $it) ? $it[6] : null;
foreach ($secimg as $rurl) {
// img height=200px src=https://static.wixstatic.com/media/'.$newtxt[0].'/
$postarr = array(
'post_title' = wp_strip_all_tags($title),
'post_name' = $title,
'post_content' = $description,
'post_type' = 'product',
'post_status' = 'publish',
);
$insert_id = wp_insert_post($postarr, true);
foreach ($secimg as $rurl) {
if($rurl){
// img height=200px src=https://static.wixstatic.com/media/'.$newtxt[0].'/
$image_url = https://static.wixstatic.com/media/;
$image_url .= $rurl;//This is the sanitized image url.
$urlimg = download_url( $image_url);
update_post_meta($insert_id, '_product_image_gallery', implode(',', array_keys($urlimg)));
//update_post_meta($post_id, array_push($post_id, '_product_image_gallery', $value ));
}
}
//set Product Category
wp_set_object_terms($insert_id, $category, 'product_cat');
//set product type
wp_set_object_terms($insert_id, 'simple', 'product_type');
update_post_meta( $insert_id, '_price', $price );
update_post_meta($insert_id, '_sku', $stock);
update_post_meta($insert_id, 'total_sales', '0');
}// End first foreach
}
}?
Topic woocommerce-offtopic array media-library attachments posts Wordpress
Category Web