Create Product Programmatically

No matter if this snippet suits your needs or not, it’s still interesting to see how you can create a brand new WooCommerce product programmatically / automatically when a certain even triggers.

In this case, we’ll see how to generate a brand new product, set its featured image, price, category, title, and more as soon as a plugin is activated in WordPress. This would be super useful in many cases where product needs to be crested automatically created.

Of course, you can customize the code and use it with different triggers. For example, you may need to create a new product automatically when each phone product needs always a matching case product, just with a different title. Or maybe you want to tie product creation once an order is placed.

Either way, enjoy!

**
 * Activate the plugin.
 */
function pluginprefix_activate() {
$post_id = wp_insert_post( array(
'post_title' => 'Donation',
'post_content' => 'Accepting Donation using woocommerce',
'post_status' => 'publish',
'post_type' => "product",
)
);
$metas = array(
'_visibility' => 'visible',
'_stock_status' => 'instock',
'total_sales' => '0',
'_downloadable' => 'no',
'_virtual' => 'yes',
'_regular_price' => '',
'_sale_price' => '',
'_purchase_note' => '',
'_featured' => 'no',
'_weight' => '',
'_length' => '',
'_width' => '',
'_height' => '',
'_sku' => '',
'_product_attributes' => array(),
'_sale_price_dates_from' => '',
'_sale_price_dates_to' => '',
'_price' => '0',
'_sold_individually' => '',
'_manage_stock' => 'no',
'_backorders' => 'no',
'_stock' => ''
);
foreach ($metas as $key => $value) {
update_post_meta($post_id, $key, $value);
}    
}
register_activation_hook( __FILE__, 'pluginprefix_activate' );