Retrieving WooCommerce Variation IDs for Expiration Logic
When extending WooCommerce to handle time-sensitive inventory, you often need to programmatically access specific variation metadata. Your goal is to retrieve the _text_field_date_expire meta value for every variation of a product and compare it against the current timestamp. However, simply iterating through your products isn't enough; you must also isolate the individual variations within those products.
WooCommerce stores variation data as child posts in the post_type hierarchy. A standard WordPress query will return the parent product post ID, but to access the specific logic for a variation, you need its unique numeric ID. The most efficient way to iterate through all variations attached to a specific product is by querying the wc_product_variation taxonomy or directly filtering posts where post_parent matches the product ID and post_type is product_variation.
Here is a robust pattern to achieve this in your theme's functions.php file. This approach loops through every variation of a given product, retrieves your custom meta, and evaluates expiration status without needing to manually construct complex queries.
add_action( 'init', 'check_expired_variations' );
function check_expired_variations() {
// Get all products (or filter by specific category/type if needed)
$products = wc_get_products( [
'limit' => -1,
'type' => 'variable',
'status' => 'publish',
] );
foreach ( $products as $product ) {
// Retrieve all variations for the current product
$variations = wc_get_product( $product->get_id() )->get_children();
foreach ( $variations as $variation ) {
// Get the unique variation ID
$variation_id = $variation->get_id();
// Retrieve your custom expiration meta
$expiration_date = get_post_meta( $variation_id, '_text_field_date_expire', true );
if ( ! empty( $expiration_date ) ) {
$expiration_timestamp = strtotime( $expiration_date );
$current_timestamp = time();
if ( $current_timestamp > $expiration_timestamp ) {
// Logic to delete or disable the expired variation
wp_delete_post( $variation_id, true );
// Optional: Remove associated attributes from product to prevent broken links
$product->sync_attributes();
}
}
}
}
}
The core of this solution relies on wc_get_product and its get_children() method. This returns an array of WC_Product_Variation objects, each containing a valid $variation_id. Once you have the ID, standard WordPress functions like get_post_meta work exactly as expected, returning the datetime string stored in your custom field.
A critical trade-off exists in how you handle the deletion logic. Using wp_delete_post( $variation_id, true ) permanently removes the variation from the database. This is appropriate for a "hard" expiration policy where the product should no longer exist once its date passes. However, this action will also orphan any existing cart items or orders that contained that specific variation ID. If you have an e-commerce platform that relies on historical order data integrity, permanently deleting posts can cause issues with order summaries displaying incorrect quantities or broken links to products.
If your requirement is to disable the variation rather than delete it, replace the deletion line with wc_delete_product( $variation_id ) if using a dedicated function, or simply update the product status to 'draft' via $product->set_status('draft'). This preserves the data for audit trails while preventing new purchases.
Another potential pitfall is timezone handling. The datetime-local input type provides a string like 2023-12-31T23:59:59, but the interpretation of that time depends on the server's timezone settings versus the user's local time during form submission. Ensure your server's date_default_timezone_set() is configured correctly relative to your business logic, or explicitly parse the input string with a specific timezone offset before converting it to a Unix timestamp.
For more complex scenarios involving high-volume products, running this check on every page load via the init hook can be resource-intensive. In such cases, consider moving this logic to a cron job that runs daily or hourly using wp_schedule_event. This decouples the heavy processing from user interactions, ensuring your store remains responsive while still managing expired inventory automatically.