Published on

Add WooCommerce product programmatically

Authors

WooCommerce gives us a very flexible option to add/modify products/orders/payments. we can manage it directly by the admin panel of WordPress or some tasks using the code. here we’ll see all the options that we can use for adding the products to WooCommerce using coding/program.

Add Product WooCommerce product is one of the custom post types of WordPress name product.so basically we need to insert post to WordPress with product type post. for that we can use wp_insert_post()

this function has two parameters:

$postarry :An array of elements that make up a post to update or insert.
$wp_error : Whether to return a WP_Error on failure. optional: default value is false( if false then WP_Error will not return)
$post_id = wp_insert_post(array(
    'post_title' => 'Test Product',
    'post_type' => 'product',
    'post_staus' = > 'draft', 
    'post_content' => 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.',
    'post_excerpt' => 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.'
));

For more option, you can see here. this function will add the product(post type) and return the id of that product using that you can add/update other meta/options.now we add/update product meta information.

Note: There might be one case when your product is not going to insert . for example I have added key post_content but my returning array $single['post_content'] (this data come from some API or form request) and it's not defined, it'll not add product. so you have to put validation isset($single['post_content']).

Add/Update Product meta

// set product is simple/variable/grouped
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', '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' );
wc_update_product_stock($post_id, $single['qty'], 'set');
update_post_meta( $post_id, '_backorders', 'no' );
// update_post_meta( $post_id, '_stock', $single['qty'] );

these are options for simple WooCommerce products. in this code, the last line is commented you can see. there's one problem while managing quantity which is even if your quantity become 0 still product status will be in stock but the stock is 0. if you manage quantity through codding. so what you can do is simply use wc_ipdate_product_stock() function. whenever you need to update your quantity through codding.

Add Feature/Gallery Image Now we will attach Feature image and gallery image to the products. here we have two options either using get_file_contents/copy or CURL. if your server has enabled allow_url_fopen then you can use get_file_contents/copy otherwise you need to use CURL. which I added in below with commented code.

/**
 * Attach images to product (feature/ gallery)
 */
function attach_product_thumbnail($post_id, $url, $flag){

    /*
     * If allow_url_fopen is enable in php.ini then use this
     */
    $image_url = $url;
    $url_array = explode('/',$url);
    $image_name = $url_array[count($url_array)-1];
    $image_data = file_get_contents($image_url); // Get image data

  /*
   * If allow_url_fopen is not enable in php.ini then use this
   */


  // $image_url = $url;
  // $url_array = explode('/',$url);
  // $image_name = $url_array[count($url_array)-1];

  // $ch = curl_init();
  // curl_setopt ($ch, CURLOPT_URL, $image_url);

  // // Getting binary data
  // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  // curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

  // $image_data = curl_exec($ch);
  // curl_close($ch);



  $upload_dir = wp_upload_dir(); // Set upload folder
    $unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); //    Generate unique name
    $filename = basename( $unique_file_name ); // Create image file name

    // Check folder permission and define file location
    if( wp_mkdir_p( $upload_dir['path'] ) ) {
        $file = $upload_dir['path'] . '/' . $filename;
    } else {
        $file = $upload_dir['basedir'] . '/' . $filename;
    }



    // Create the image file on the server
    file_put_contents( $file, $image_data );

    // Check image file type
    $wp_filetype = wp_check_filetype( $filename, null );

    // Set attachment data
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name( $filename ),
        'post_content' => '',
        'post_status' => 'inherit'
    );

    // Create the attachment
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

    // Include image.php
    require_once(ABSPATH . 'wp-admin/includes/image.php');

    // Define attachment metadata
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

    // Assign metadata to attachment
    wp_update_attachment_metadata( $attach_id, $attach_data );

    // asign to feature image
    if( $flag == 0){
        // And finally assign featured image to post
        set_post_thumbnail( $post_id, $attach_id );
    }

    // assign to the product gallery
    if( $flag == 1 ){
        // Add gallery image to product
        $attach_id_array = get_post_meta($post_id,'_product_image_gallery', true);
        $attach_id_array .= ','.$attach_id;
        update_post_meta($post_id,'_product_image_gallery',$attach_id_array);
    }

}
//set product feature image
attach_product_thumbnail($post_id, $single['coverImage'], 0);

foreach($single['screenshots'] as $screenshots){
//set gallery image
attach_product_thumbnail($post_id, $screenshots['url_original'], 1);
}

Add Product Category Now, add the categories to a product. If the category exists then assign else add category then assign it.

foreach($single['genres'] as $prod_cat){
    if(!term_exists($prod_cat, 'product_cat')){
        $term = wp_insert_term($prod_cat, 'product_cat');
        array_push($tag, $term['term_id']);
    } else {
        $term_s = get_term_by( 'name', $prod_cat, 'product_cat' );
        array_push($tag , $term_s->term_id);
    }
}

This what you need to add WooCommerce product via programming.