Skip to content

Instantly share code, notes, and snippets.

@BKeanu1989
Last active March 14, 2024 15:30
Show Gist options
  • Save BKeanu1989/3e0a52728da94fc462fd5fa86e8a78dc to your computer and use it in GitHub Desktop.
Save BKeanu1989/3e0a52728da94fc462fd5fa86e8a78dc to your computer and use it in GitHub Desktop.
adding woocommerce productgs programmatically/ via code
function insert_product ($product_data)
{
$post = array( // Set up the basic post data to insert for our product
'post_author' => 1,
'post_content' => $product_data['description'],
'post_status' => 'publish',
'post_title' => $product_data['name'],
'post_parent' => '',
'post_type' => 'product'
);
$post_id = wp_insert_post($post); // Insert the post returning the new post id
if (!$post_id) // If there is no post id something has gone wrong so don't proceed
{
return false;
}
update_post_meta($post_id, '_sku', $product_data['sku']); // Set its SKU
update_post_meta( $post_id,'_visibility','visible'); // Set the product to visible, if not it won't show on the front end
wp_set_object_terms($post_id, $product_data['categories'], 'product_cat'); // Set up its categories
wp_set_object_terms($post_id, 'variable', 'product_type'); // Set it to a variable product type
insert_product_attributes($post_id, $product_data['available_attributes'], $product_data['variations']); // Add attributes passing the new post id, attributes & variations
insert_product_variations($post_id, $product_data['variations']); // Insert variations passing the new post id & variations
}
function insert_product_attributes ($post_id, $available_attributes, $variations)
{
foreach ($available_attributes as $attribute) // Go through each attribute
{
$values = array(); // Set up an array to store the current attributes values.
foreach ($variations as $variation) // Loop each variation in the file
{
$attribute_keys = array_keys($variation['attributes']); // Get the keys for the current variations attributes
foreach ($attribute_keys as $key) // Loop through each key
{
if ($key === $attribute) // If this attributes key is the top level attribute add the value to the $values array
{
$values[] = $variation['attributes'][$key];
}
}
}
$values = array_unique($values); // Filter out duplicate values
wp_set_object_terms($post_id, $values, 'pa_' . $attribute);
}
$product_attributes_data = array(); // Setup array to hold our product attributes data
foreach ($available_attributes as $attribute) // Loop round each attribute
{
$product_attributes_data['pa_'.$attribute] = array( // Set this attributes array to a key to using the prefix 'pa'
'name' => 'pa_'.$attribute,
'value' => '',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
);
}
update_post_meta($post_id, '_product_attributes', $product_attributes_data); // Attach the above array to the new posts meta data key '_product_attributes'
}
function insert_product_variations ($post_id, $variations)
{
foreach ($variations as $index => $variation)
{
$variation_post = array( // Setup the post data for the variation
'post_title' => 'Variation #'.$index.' of '.count($variations).' for product#'. $post_id,
'post_name' => 'product-'.$post_id.'-variation-'.$index,
'post_status' => 'publish',
'post_parent' => $post_id,
'post_type' => 'product_variation',
'guid' => home_url() . '/?product_variation=product-' . $post_id . '-variation-' . $index
);
$variation_post_id = wp_insert_post($variation_post); // Insert the variation
foreach ($variation['attributes'] as $attribute => $value) // Loop through the variations attributes
{
$attribute_term = get_term_by('name', $value, 'pa_'.$attribute); // We need to insert the slug not the name into the variation post meta
update_post_meta($variation_post_id, 'attribute_pa_'.$attribute, $attribute_term->slug);
}
update_post_meta($variation_post_id, '_price', $variation['price']);
update_post_meta($variation_post_id, '_regular_price', $variation['price']);
}
}
function insert_products ($products)
{
if (!empty($products)) // No point proceeding if there are no products
{
array_map('insert_product', $products); // Run 'insert_product' function from above for each product
}
}
$json = file_get_contents('my-product-data.json'); // Get json from sample file
// $products_data = json_decode($json_file, true); // Decode it into an array
echo json_last_error();
// if(get_magic_quotes_gpc()){
// $d = stripslashes($json);
// }else{
// $d = $json;
// }
$d = json_decode($d,true);
$products_data = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json), true );
echo "<h1>json</h1>";
echo "<pre>";
print_r($json);
echo "</pre>";
echo "<h1>Product data</h1>";
echo "<pre>";
var_dump($products_data);
echo "</pre>";
insert_products($products_data);
@appsdevpk
Copy link

Your code saved my life.

@aksld
Copy link

aksld commented Aug 2, 2019

Hello,

I'm using something like that :

$variation_data = array(
	array(
		'attributes'    => array(
			'size' => 'l',
		),
		'sku'           => '',
		'regular_price' => '22.00',
		'sale_price'    => '',
		'stock_qty'     => 10,
	),
);

insert_product_attributes( 34, array( 'size' ), $variation_data );
insert_product_variations( 34, $variation_data );

My array parameter is good ?

I want to add for a product one attribute size and two variations S and M. It's posible ?

Thanks :)

@Alex-hi-2019
Copy link

Please send me the sample json file "my-product-data.json".
It's really helpful for me.

@razvanFrandes
Copy link

razvanFrandes commented Apr 4, 2020

Hello, can you please share an json example, i tried to reverse engineer but without success.
Here is what i got so far:

$product_data = array(
        'sku' => '123SKU',
        'categories' => array('size', 'color'),
        'available_attributes' => array('size', 'color'),
        'variations' => array( 
            'size' => array(
                'attributes' => array( 'XL', 'M', 'S' ), 
            ),
            'color' => array(
                'attributes' => array( 'Blue', 'Red', 'Green' )  
            )
        )
)

Thank You.;

@monib102
Copy link

Hi.
I can create my product with php successfully, but now I want to set product's attribute and I can't.
To be more clear:
I create some custom attributes in wordpress admin panel, and I want to add values for those attributes in my product, by php.

any help?

@egbamddeveloper
Copy link

{
product_id: product.id,
available_attributes: ["color", "size"],
variation_data: {
attributes: {
color: "Red",
size: "M",
},
sku: "",
regular_price: 200,
sale_price: "",
stock_qty: 8,
},
},

this example to inset attributes and variables in react native.

Thanks man very much :)

@therealshubham
Copy link

product

Can you send me too please? shubgupp@gmail.com

@babek56
Copy link

babek56 commented Aug 9, 2021

Please send me the sample json file
It's really helpful for me. I write a little of this but its not complete
best wishes and thanks

@aschultzapiam
Copy link

Would be nice if you converted this to use WC 3.0 CRUD operations. Much cleaner :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment