WooCommerce 3.0+
To Delete a Variation (source code):
$variation_product = wc_get_product( 1239 );
$variation_product->delete( true );
// true = force delete
// false = move to trash
Auto-Removing Attributes from Variable Product
The Size values in your screenshot are linked to your Variable Product, and not the individual Variations.
Deleting a Variation will therefore not remove the associated Attributes from the parent product, as you still have the choice of making new Variations with those Attributes (the possibility of adding an XL shirt later on is still there).
However, if you want the associated Variation Attributes to be automatically deleted after deleting a Variation, here's a code suggestion on how to do it:
Deleting All Variation Attributes from original Variable Product:
Variable Product attributes (before): XS, S, M, L, XL
Variation attributes: XL
Variable Product attributes (after): XS, S, M, L
// Variable Product
$product = wc_get_product( 1234 );
$product_attributes = $product->get_attributes(); // XS, S, M, L, XL
// XL Variation
$variation = wc_get_product( 1239 );
$variation_attributes = $variation->get_attributes(); // XL
// loop through Variation attributes (here: attribute is Size, values are XL)
foreach( $variation_attributes as $attribute => $value ){
// Fetch attributes: Size => XS, S, M, L, XL
$product_attribute_options = $product_attributes[ $attribute ]->get_options();
// remove "XL" option
remove_value_from_array( $product_attribute_options, $value );
// reassign Size WITHOUT "XL" option
$product_attributes[ $attribute ]->set_options( $product_attribute_options );
// clone WC_Product_Attribute object to tell WooCommerce it has changed (otherwise save() won't work)
$product_attributes[ $attribute ] = clone $product_attributes[ $attribute ];
}
// assign the new attributes object to main Variable product
$product->set_attributes( $product_attributes );
$product->save(); // save to DB
$variation->delete(); // finally, delete variation
// credit: https://stackoverflow.com/a/11982622
function remove_value_from_array(& $array, $value){
foreach (array_keys($array, $value, true) as $key) {
unset($array[$key]);
}
}
Instead of cloning the object, you can also create a new WC_Product_Attribute()
instance and assign all the necessary data manually.