Last active
February 4, 2025 10:54
-
-
Save femiyb/7da2e40ef624af0d7aa5ee0716b62b20 to your computer and use it in GitHub Desktop.
Set Expiration Date for a Virtual Product in WooCommerce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Set expiration date for virtual products when the order is marked complete | |
add_action('woocommerce_order_status_completed', 'set_user_virtual_product_expiration', 10, 1); | |
function set_user_virtual_product_expiration($order_id) { | |
$order = wc_get_order($order_id); | |
$user_id = $order->get_user_id(); | |
if (!$user_id) return; // Ensure it's a registered user | |
foreach ($order->get_items() as $item_id => $item) { | |
$product = $item->get_product(); | |
if ($product->is_virtual()) { | |
$product_id = $product->get_id(); | |
$expiration_date = strtotime('+1 year', strtotime($order->get_date_completed())); | |
// Save expiration date per user and per product | |
update_user_meta($user_id, '_product_expiration_date_' . $product_id, $expiration_date); | |
} | |
} | |
} | |
// Restrict access to virtual product if expired | |
add_action('template_redirect', 'restrict_access_to_expired_products'); | |
function restrict_access_to_expired_products() { | |
if (!is_user_logged_in()) return; | |
global $post; | |
$user_id = get_current_user_id(); | |
$product_id = $post->ID; | |
// Get expiration date specific to this user and product | |
$expiration_date = get_user_meta($user_id, '_product_expiration_date_' . $product_id, true); | |
if ($expiration_date && time() > $expiration_date) { | |
wp_die('Access to this product has expired. Please repurchase to regain access.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment