Skip to content

Instantly share code, notes, and snippets.

@Preciousomonze
Last active June 27, 2024 09:07
Show Gist options
  • Save Preciousomonze/1ab18dd50162e1d140ac9ab7f8dff9fb to your computer and use it in GitHub Desktop.
Save Preciousomonze/1ab18dd50162e1d140ac9ab7f8dff9fb to your computer and use it in GitHub Desktop.
A snippet code for creating Products, use at your discretion
<?php
/**
* Creates a woocommerce product from a loystar product
*
* @param int $product_id(optional
* @param array $product_list(optional) | the loystar product list, this saves resources incase this function is called in the loop, the
* endpoint shouldn't be called everything
* @param bool $link_product(optional) | if set to true, the created woocommerce product will be linked to the loystar product
* @param bool $update(optional) | if set to true, it updates an existing product
* @param bool $only_import(optional) | if set to true, it updates only products that were imported from loystar direct.relevant when $update is true
* //(not in use)param bool $product_args(optional) | the parts of the loystar products you want to edit, works when update is true, leave empty if you want all to be updated
* @param bool $allow_duplicate(optional) | if set to true, it'll allow a product created already to be created again
* @return int
*/
public function add_woo_product($product_id = 0, $update = false){
$p = 0;
$wc_p = new WC_Product($p);//wc_get_product();
if($count_variants > 0)
$wc_p = new WC_Product_Variable($p);//variable product
//set stuff
if(!$update){//only when newly added, these are default stuff
$wc_p->set_stock_status('instock'); // in stock or out of stock value
$wc_p->set_backorders('no');
$wc_p->set_reviews_allowed(true);
$wc_p->set_sold_individually(false);
$wc_p->set_status("publish"); // can be publish,draft or any wordpress post status
$wc_p->set_catalog_visibility('visible'); // add the product visibility status
}
if(!$update || ($update && $only_import) ){//quite confusing ba?, if its a new product or its an update that was imported
$wc_p->set_name($l_product['name']);
$wc_p->set_description($l_product['description']);
try{//to prevent error
$wc_p->set_sku($l_product['sku']); //can be blank in case you don't have sku, but You can't add duplicate sku's
}
catch(Exception $e){
wc_loystar()->set_exception($e);
}
$wc_p->set_price($l_product['price']); // set product price
$wc_p->set_regular_price($l_product['original_price']); // set product regular price
$wc_p->set_manage_stock($l_product['track_inventory']); // true or false
$wc_p->set_stock_quantity($l_product['quantity']);
if(!$update)//if its an update, for now, ignore
$wc_p->set_category_ids(array($this->add_woo_cat_from_loystar($l_product['merchant_product_category_id']) ) ); // array of category ids,
//for the image part
if(!$update){
$product_images_ids = array(); // define an array to store the media ids.
$images = array($l_product['picture']); // images url array of product
foreach($images as $image){
if(empty(trim($image)))
continue;
$media_id = $this->upload_media($image); // calling the uploadMedia function and passing image url to get the uploaded media id
if($media_id){
$product_images_ids[] = $media_id; // storing media ids in a array.
}
}
if($product_images_ids){
$wc_p->set_image_id($product_images_ids[0]); // set the first image as primary image of the product
//in case we have more than 1 image, then add them to product gallery.
if(count($product_images_ids) > 1){
$wc_p->set_gallery_image_ids($product_images_ids);
}
}
}
else{//update
if( $this->get_equiv_loystar_product_image($wc_p->get_image_id()) != $l_product['picture']){//image has been changed,
$media_id = $this->upload_media($l_product['picture']);
if($media_id)
$wc_p->set_image_id($media_id);
}
}
}
else{//for now, products that weren't imported, we only update the quantity
$wc_p->set_stock_quantity($l_product['quantity']);
}
########## done with images
$wc_p_id = $wc_p->save(); //save the product
if(!$update){//a new product
update_post_meta($wc_p_id,WC_LS_PRODUCT_IMPORT_META_KEY,$loystar_product_id);
//link
if($link_product){
if( $c_already_linked_id < 1)//not linked yet
update_post_meta($wc_p_id,WC_LS_PRODUCT_META_KEY,$loystar_product_id);
}
}
//now check if the product has variants or if its an update that wasn't imported
if($count_variants < 1 || ($update && !$only_import))
return $wc_p_id;
//so it has, since the code got here :)
$l_v_products = $l_product['variants'];
//add product attributes
###################################################
$attributes = wc_loystar()->sort_woo_attr_from_loystar_variants($l_v_products);
if($attributes){
$product_attributes=array();
foreach($attributes as $attribute){
$a_name = $attribute["name"];
$attr = wc_sanitize_taxonomy_name(stripslashes($a_name)); // remove any unwanted chars and return the valid string for taxonomy name
$attr = 'pa_'.$attr; // woocommerce prepend pa_ to each attribute name
###################################
//create product attr
if(wc_loystar()->create_woo_product_attribute($a_name) == 0){//attr already exists,do nothing
}
if($attribute["options"]){
foreach($attribute["options"] as $option){
//If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
if( ! taxonomy_exists( $attr ) ){
register_taxonomy(
$attr,
'product',
array(
'hierarchical' => false,
'label' => ucfirst( $attr ),
'query_var' => true,
'rewrite' => array( 'slug' => $attr), // The base slug
)
);
}
$relate = wp_set_object_terms($wc_p_id,$option,$attr,true); // save the possible option value for the attribute which will be used for variation later
if(is_wp_error($relate)){//an error while setting relationship,this is bad for business :)
//delete the product
wc_loystar()->delete_woo_product($wc_p_id,true);//delete permanently
return 0;
}
}
}
$product_attributes[sanitize_title($attr)] = array(
'name' => sanitize_title($attr),
'value' => $attribute["options"],
'position' => $attribute["position"],
'is_visible' => $attribute["visible"],
'is_variation' => $attribute["variation"],
'is_taxonomy' => '1'
);
}
update_post_meta($wc_p_id,'_product_attributes',$product_attributes); // save the meta entry for product attributes
}
#########################################################
//add product variations
//############################################
$variations = wc_loystar()->sort_woo_variations_from_loystar_variants($l_v_products);
if($variations){
//add variation
$wc_p_variations = $this->create_woo_product_variations($wc_p_id,$variations,$link_product,$update,$only_import,$allow_duplicate);
if(!$update){//only matters if it's a new product
if(count($wc_p_variations) != count($variations)){//not all variations were successfully added
//an error,delete the whole product, just to be safe :)
wc_loystar()->delete_woo_product($wc_p_id,true);//delete permanently
return 0;
}
}
}
#########################################################################
return $wc_p_id;
}
/**
* Create a product variation for a defined variable product ID.
*
* @param int $product_id | Post ID of the product parent variable product.
* @param array $variations_data | The variations data to insert in the product.
* @param bool $link_product(optional),true | if set to true, the created woocommerce product will be linked to the loystar product
* @param bool $update(optional) if set to true, it updates an existing product
* @param bool $only_import(optional) if set to true, it updates only products that were imported from loystar direct.relevant when $update is true
* @param bool $allow_duplicate(optional) if set to true, it'll allow a product created already to be created again
* @return array | variation ids
*/
public function create_woo_product_variations( $product_id, $variations_data, $link_product = true,$update = false,$only_import = false,$allow_duplicate = false){
try{
$data = array();
$already_linked_id = $this->get_actual_linked_woo_products(0,true,$only_import,true);
$c_already_linked_id = count($already_linked_id);
if(!$allow_duplicate && !$update){//check
if($c_already_linked_id > 0 )//already exists, prevent//this is how i do it, assuming that variants from loystar cant have duplicate id, as i was told
return array();
}
// Get the Variable product object (parent)
$product = wc_get_product($product_id);
$variation_post = array(
'post_title' => $product->get_title(),
'post_name' => 'product-'.$product_id.'-variation',
'post_status' => 'publish',
'post_parent' => $product_id,
'post_type' => 'product_variation',
'guid' => $product->get_permalink()
);
// Iterating through the variations data
foreach($variations_data as $variation_data){
$loystar_variant_id = $variation_data['_loystar_variant_id'];
// Creating the product variation
$variation_id = 0;
if($update){//update
$variation_ids = $this->get_actual_linked_woo_products($loystar_variant_id,true,$only_import,true);
if(is_bool($variation_ids))//api error
continue;//on to the next one!
$variation_id = (int)$variations_ids[0];
}
else
$variation_id = wp_insert_post( $variation_post );
// Get an instance of the WC_Product_Variation object
$variation = new WC_Product_Variation( $variation_id );
// Iterating through the variations attributes
foreach ($variation_data['attributes'] as $attribute ){
$term_name = $attribute['option'];
$taxonomy = strtolower('pa_'.$attribute['name']); // The attribute taxonomy
// If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
if( ! taxonomy_exists( $taxonomy ) ){
register_taxonomy(
$taxonomy,
'product_variation',
array(
'hierarchical' => false,
'label' => ucfirst( $taxonomy ),
'query_var' => true,
'rewrite' => array( 'slug' => '$taxonomy'), // The base slug
)
);
}
// Check if the Term name exist and if not we create it.
if( ! term_exists( $term_name, $taxonomy ) )
wp_insert_term( $term_name, $taxonomy ); // Create the term
$term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get the term slug
// Get the post Terms names from the parent variable product.
$post_term_names = wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
// Check if the post term exist and if not we set it in the parent variable product.
if( ! in_array( $term_name, $post_term_names ) )
wp_set_object_terms( $product_id, $term_name, $taxonomy, true );
// Set/save the attribute data in the product variation
update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug );
}
## Set/save all other data
if(!$update || ($update && $only_import) ){//quite confusing ba?, if its a new product or its an update with only import
// SKU
if( !empty( $variation_data['sku'] ) )
$variation->set_sku( $variation_data['sku'] );
// Prices
if( empty( $variation_data['sale_price'] ) ){
$variation->set_price( $variation_data['regular_price'] );
} else {//theres awuuf
$variation->set_price( $variation_data['sale_price'] );
$variation->set_sale_price( $variation_data['sale_price'] );
}
$variation->set_regular_price( $variation_data['regular_price'] );
// Stock
if( !empty($variation_data['stock_qty']) ){
$variation->set_stock_quantity( $variation_data['stock_qty'] );
$variation->set_manage_stock(true);
$variation->set_stock_status('');
} else {
$variation->set_manage_stock(false);
}
}
else{//its casual change, only inventory
$variation->set_stock_quantity( $variation_data['stock_qty'] );
}
$id = $variation->save(); // Save the data
if($id > 0)
$data[] = $id;//saved
//lin
if($l
ink_product){//link variation to loystar variant
update_post_meta($id,WC_LS_PRODUCT_VAR_META_KEY,$loystar_variant_id);
update_post_meta($id,WC_LS_PRODUCT_VAR_BRANCH_META_KEY,$variation_data['_business_branch_id']);
f(!$update)//show it was imported
update_post_meta($id,WC_LS_PRODUCT_VAR_IMPORT_META_KEY,$loystar_variant_id);
}
}//end of parent loop
return $data;
}
catch(Exception $ex){
return array();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment