Insert new woocommerce product programmatically
How to insert brand new Woocommerce product programmatically? Sometimes you need your own product importer. You may read database, XML, JSON, CSV, XLS, XLSX, ODS, absolutely anything. Now you got all your products in memory or cache or your temporary file and what’s next? You need to add this product to Woocommerce…
Well, the product is – like almost anything in WordPress – post type with specific taxonomy and meta data set. So, first things first, insert your new post:
1 2 3 4 5 6 |
$post_id = wp_insert_post( array( 'post_title' => 'Great new product', 'post_content' => 'Here is content of the post, so this is our great new products description', 'post_status' => 'publish', 'post_type' => "product", ) ); |
Of course this is not everything, that would be too easy. Now we need to add some meta information to the product post and that is why, we take care of our new posts ID.
Now we need to relate our post, to proper term and taxonomy. The function we need is wp_set_object_terms
and we will use it like this:
1 |
wp_set_object_terms( $post_id, 'simple', 'product_type' ); |
This will relate our post as a simple product. Please be careful, because this function will create term/taxonomy if those doesn’t exists. First you must know you are running WordPress with Woocommerce enabled.
update_post_meta
function. There is no built-in function to do it with one call, so be prepared… Three, two, one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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', '' ); update_post_meta( $post_id, '_length', '' ); update_post_meta( $post_id, '_width', '' ); update_post_meta( $post_id, '_height', '' ); update_post_meta( $post_id, '_sku', '' ); 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', '' ); update_post_meta( $post_id, '_sold_individually', '' ); update_post_meta( $post_id, '_manage_stock', 'no' ); update_post_meta( $post_id, '_backorders', 'no' ); update_post_meta( $post_id, '_stock', '' ); |
And that’s it. You have a brand new product.
In practice. Of course I do realize it isn’t that easy in practice. Probably you will need a loop to insert much more products than one. Then you need to use some fields from that array… Let’s say we’ve got an array like that:
1 2 3 4 5 |
$single_product = array( 'Name' => 'Product A', 'Description' => 'This is a product A', 'SKU' => '10020030A', ); |
and additionally we let user to choose – what user (some other one) will be responsible for import. Then we need to do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
$user_id = get_current_user(); // this has NO SENSE AT ALL, because wp_insert_post uses current user as default value $user_id = $some_user_id_we_need_to_use; // So, user is selected.. foreach( $products as $item ) { $post_id = wp_insert_post( array( 'post_author' => $user_id, 'post_title' => $item['Name'], 'post_content' => $item['Description'], 'post_status' => 'publish', 'post_type' => "product", ) ); wp_set_object_terms( $post_id, 'simple', 'product_type' ); 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', '' ); update_post_meta( $post_id, '_length', '' ); update_post_meta( $post_id, '_width', '' ); update_post_meta( $post_id, '_height', '' ); update_post_meta( $post_id, '_sku', $item['SKU'] ); 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', '' ); update_post_meta( $post_id, '_sold_individually', '' ); update_post_meta( $post_id, '_manage_stock', 'no' ); update_post_meta( $post_id, '_backorders', 'no' ); update_post_meta( $post_id, '_stock', '' ); } |
That should work.
One last word about product importing. This is a bit time-consuming. I wrote two importers in a last week, I know what I’m talking about. They work like a charm, but I needed to use AJAX. Thanks to that, I was able to import as many products as I want (then I split the list to not exceed time execution limit) and – as a second bird with one stone – I got nice progress bar at the frontend, so WP admin was able to see the exact process of importing.
30 Comments
Daniel
Thanks! Very useful article. Great starting spot for creating my own product upload for for woocommerce.
Radenko
I’m building new web site with web shop, it is not published yet. I need to make custom importer, Is there any chance to share one of yours importers?
Thank You
Best Regards
Łukasz Nowicki
Hi, I am sorry but I wrote it in my working hours for my company and I do not own rights to those importers.
sreeDev
Hi ,I added the products from quickbook pos application to woocommerce.Everything was updated successfully.But there is a problem on sales dates.I added the code as below
update_post_meta( 8, ‘_sale_price_dates_from’, 1473638400 );
update_post_meta( 8, ‘_sale_price_dates_to’, 1473638400 );
Its a future timestamp .But its showing the products always on sale .Any help ??
Łukasz Nowicki
Hi, there are many reasons why this may not work. First thought – please install wp debug cron to see if there are any planned tasks and deactivate/activate woocommerce. It’s a bit complicated to answer unseen problems 🙂
Pankaj
I am trying to assign the category to product using wp_set_object_terms method, but it return the error with invalid taxonomy, I tried in every way to make it done, but not working,
Any help would be apprecialble
Łukasz Nowicki
I am sorry, I can’t predict how you do it without seeing the source code, so I can’t help. However I will write a short article about adding products to categories today.
Ok., see this Assign Woocommerce product categories programmatically. Hope that helps.
Pavlo
Thank you. Very useful.
Manalee
Thank you,this is very useful blog to create our own products.
Linkhouse Media
Great article! Exactly what I needed to turn member input into products with admin approval. In case anyone is wondering, you can add the product short description using:
post_excerpt
in thewp_insert_post
function. Cheers!Juergen
Thanks for the hints.
I use my own API (link) to run commands against wordpress/woocommerce.
That way I never run into problem with max exicution times -> no Ajax needed.
All my importers run local (Mysql/PHP) whereas the shop runs on a remote server.
Vladimir
Thanks for sharing this.
Btw, there is a typo in the text: ‘Fiannly’ instead of ‘Finally’.
Łukasz Nowicki
Thank you Vladimir for pointing this out, I fixed it
samuel
Very nice and helpful article.
I would like to ask if I am going to add a multiple insert using your code?
Is there a function in wordpress that can handle multiple insert?
Łukasz Nowicki
Unfortunately not. You have to loop through those functions and insert products one by one
Paul Green
Hi, Sorry to ask a basic question. I am a javascript developer just getting to grips with WordPress. I have a wordpress website that I want to create a product from an event on the form. I can call jQuery.ajax or equiv and I know the parmeters to pass.
How do I call a PHP file that has access to the WC functions ? Sorry I know this is a very basic question, but I am learning PHP and WordPress at the same time.
Łukasz Nowicki
Paul, it’s not that basic, but it also isn’t very hard.
The right way to do ajax calls in WordPress environment is this:
– first, you need a place to store your PHP code. You may write a plugin or use functions.php in your theme (of course you will need to use child-theme if it isn’t your theme)
– then, you need to hook at least one of those actions:
wp_ajax_something and wp_ajax_nopriv_something
First is used for logged users (wp_ajax_something) and second is used for non-logged users (wp_ajax_nopriv_something).
I assume that only logged in user may be able to add product, so:
add_action( ‘wp_ajax_pauladdproduct’, ‘pauladdproduct’ );
and then:
function pauladdproduct() {
# here you are adding a product
}
To do a proper ajax call, you will need something like this:
data = { action: ‘pauladdproduct’, value1: ‘some value’, ‘value2’: ‘another value’ };
jQuery.post( ajaxurl, data, function(response){
alert(response);
});
This should work.
Sachin
Hi Łukasz, thanks for sharing such a good and simple tutorial. Its working fine for me, can you tell us also about how to add product images and feature image.
Łukasz Nowicki
Hello Sachin, thank you for great idea for next post! 🙂 Of course I will.
Luciano
Hey, nice article! Just wondering how to insert Variable products. Which is the correct way to add variations?
Łukasz Nowicki
Luciano, variable products are, in simple terms, other post (children of product post) with specific title, IDs etc. You may find examples over the internet, for sure. Maybe I will write about it. Comment is much too small to write more. But it is similar job. Regards!
Luciano
I’ll really appreciate a code sample by you. I’ve found the way to add variations but they are not listed at frontend, just an empty select for my variations despite they are listed in admin. I think I’m missing something here like saving variation attributes. Regards!
Nilam
Thank you Łukasz for this awesome tutorial. I can now import my products from my custom xml file to the woocommerce product page. Actually I am building an importer plugin and I have one more question here. It would be really great if you can post a sample code on how to import attributes as well. Your examples are more understandable than those in the internet. Regards!
Łukasz Nowicki
Hello, thank you very much. I got a few articles in progress, please be patient, I will, for sure 🙂
Saurabh Jain
Hi Łukasz Nowicki,
Thanks for the code. I am building a custom product importer, do you know something from which I can upload .xlxs or .xls file instead of .csv any library or something?
Please let me know.
Łukasz Nowicki
Yes, of course:
https://github.com/PHPOffice/PHPExcel
And please remember in the future – google/yandex/duckduckgo/whatever are your friends 🙂
Saurabh Jain
Thanks,
Got the same thing after I posted here.
Martin Piñeiro
Hi, you could create that import script ? I have to do the same…
Saurabh Jain
Hi Łukasz Nowicki,
Have you tried something for variable products?
Łukasz Nowicki
Hi, yes of course, I did, many times 😉 however I changed my job and I don’t have a bit of time at the moment