Skip to content

Instantly share code, notes, and snippets.

@mtruitt
Last active August 19, 2019 04:48
Show Gist options
  • Select an option

  • Save mtruitt/b307547698c5db8496a0058c85630685 to your computer and use it in GitHub Desktop.

Select an option

Save mtruitt/b307547698c5db8496a0058c85630685 to your computer and use it in GitHub Desktop.
Delete Variations from Products
<?php
function delete_variations(){
// Lets grab the product type
$product_id = get_the_ID();
$product_type = WC_Product_Factory::get_product_type( $product_id );
// Lets skip everything if its not a product.
if( $product_type == false ) return;
// Lets make sure we are working with registrations
if( $product_type == 'registrations') {
// Grab the ID
$parent = wc_get_product( $product_id );
// Pull children or variations of parent
$children = $parent->get_children();
//
foreach ( $children as $child ) {
$dates = json_decode( get_post_meta( $child, 'attribute_dates', true ) );
$today = strtotime( date( 'Y-m-d' ) );
if ( $dates->type == 'range' ) {
$first_date = strtotime( $dates->dates[0] );
if ( $first_date < $today ) {
deleteProduct( $child, true );
}
} elseif ( $dates->type == 'single' ) {
$date = strtotime( $dates->date );
if ( $date < $today ) {
deleteProduct( $child, true );
}
}
}
}
}
add_action( "template_redirect", "delete_variations" );
@mtruitt
Copy link
Author

mtruitt commented Apr 25, 2019

This will delete a variation from the parent product if conditions aren't met. This instance is pulling dates used by the WooCommerce registration plugin as it does not drop off expired dates.

deleteProduct function referenced here:
https://gist.github.com/mtruitt/8e2fae133ef15706bb4728d11d9e9dcf

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