Skip to content

PHP code snippet – How to add product to wordpress programmatically?

<?php

function create_Products_Programmatically(){

	// Set number of products to create
	$number_of_products = 100;

	for ($i=1; $i <= $number_of_products; $i++) { // First we create the product post so we can grab it's ID $post_id = wp_insert_post( array( 'post_title' => 'Product ' . $i,
				'post_type' => 'product',
				'post_status' => 'publish'
			)
		);

		// Then we use the product ID to set all the posts meta
		wp_set_object_terms( $post_id, 'simple', 'product_type' ); // set product is simple/variable/grouped
		update_post_meta( $post_id, '_visibility', 'visible' );
		update_post_meta( $post_id, '_stock_status', 'instock');
		update_post_meta( $post_id, 'total_sales', '0' );
		update_post_meta( $post_id, '_downloadable', 'no' );
		update_post_meta( $post_id, '_virtual', 'yes' );
		update_post_meta( $post_id, '_regular_price', '' );
		update_post_meta( $post_id, '_sale_price', '' );
		update_post_meta( $post_id, '_purchase_note', '' );
		update_post_meta( $post_id, '_featured', 'no' );
		update_post_meta( $post_id, '_weight', '11' );
		update_post_meta( $post_id, '_length', '11' );
		update_post_meta( $post_id, '_width', '11' );
		update_post_meta( $post_id, '_height', '11' );
		update_post_meta( $post_id, '_sku', 'SKU11' );
		update_post_meta( $post_id, '_product_attributes', array() );
		update_post_meta( $post_id, '_sale_price_dates_from', '' );
		update_post_meta( $post_id, '_sale_price_dates_to', '' );
		update_post_meta( $post_id, '_price', '11' );
		update_post_meta( $post_id, '_sold_individually', '' );
		update_post_meta( $post_id, '_manage_stock', 'yes' ); // activate stock management
		wc_update_product_stock($post_id, 100, 'set'); // set 1000 in stock
		update_post_meta( $post_id, '_backorders', 'no' );
	}
}
See also  How to change canvas background color in Python tkinter?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.