Last active
November 3, 2023 16:03
-
-
Save reandimo/fb8b33650985ad248e8060fd205849fa to your computer and use it in GitHub Desktop.
Skip Renewal action in My Account for Woocommerce Subscriptions (skip next month renewal)
This file contains hidden or 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 | |
add_filter('wcs_view_subscription_actions', 'add_skip_action', 99, 3); | |
add_filter('wcs_view_subscription_actions', 'rename_default_actions', 10, 3); | |
/** | |
* Adds the customer skip action, if allowed. Ex. If next renewal is in Oct 10, when the user click this button, the next payment date will be in Nov 10. | |
* Long story short, delays next payment date 1 month for the subscription. | |
* | |
* @since 4.0.0 | |
* | |
* @param array $actions The actions a customer/user can make with a subscription. | |
* @param WC_Subscription $subscription The subscription. | |
* @param int $user_id The user viewing the subscription. | |
* | |
* @return array The customer's subscription actions. | |
*/ | |
function add_skip_action($actions, $subscription, $user_id) | |
{ | |
if (!$subscription->has_status('active')) { | |
return $actions; | |
} | |
$action_link = add_query_arg( | |
array( | |
'subscription_id' => $subscription->get_id(), | |
'skip' => true, | |
) | |
); | |
$action_link = wp_nonce_url($action_link, $subscription->get_id() . '_skip'); | |
$actions['skip'] = array( | |
'url' => $action_link, | |
'name' => 'Skip', | |
); | |
return $actions; | |
} | |
function subscription_skip_handler() | |
{ | |
global $post; | |
if (isset($_GET['subscription_id'])) { | |
$subscription = wcs_get_subscription(absint($_GET['subscription_id'])); | |
// Visiting a switch link for someone elses subscription or if the switch link doesn't contain a valid nonce | |
if (!is_object($subscription) || empty($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field($_GET['_wpnonce']), $subscription->get_id() . '_skip')) { | |
wp_redirect(remove_query_arg(array('skip'))); | |
exit(); | |
} else { | |
$date = date('Y-m-d H:i:s', $subscription->get_time('next_payment')); | |
$new_date = date('Y-m-d H:i:s', strtotime($date . ' + 1 months')); | |
try { | |
$subscription->update_dates(['next_payment' => $new_date], 'gmt'); | |
wp_cache_delete($subscription->get_id(), 'posts'); | |
$d = date('Y-m-d', $subscription->get_time('next_payment')); | |
$url = remove_query_arg(array('skip', 'subscription_id', '_wpnonce')); | |
$url = add_query_arg(array('skip_next_renewal' => $d), $url); | |
wp_redirect($url); | |
} catch (\Exception $e) { | |
wcs_add_admin_notice($e->getMessage(), 'error'); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment