Skip to content

Instantly share code, notes, and snippets.

@reandimo
Last active November 3, 2023 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reandimo/fb8b33650985ad248e8060fd205849fa to your computer and use it in GitHub Desktop.
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)
<?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