Skip to content

Instantly share code, notes, and snippets.

@jrglass
Created August 23, 2024 00:15
Show Gist options
  • Save jrglass/c0d13e85fac749f5ed56f8def9f8258c to your computer and use it in GitHub Desktop.
Save jrglass/c0d13e85fac749f5ed56f8def9f8258c to your computer and use it in GitHub Desktop.
Woo Subscriptions Function: Custom shortcode for cancel subscription button
function cwpai_cancel_user_subscription_button() {
if ( ! is_user_logged_in() ) {
echo '<p>You need to be logged in to cancel your subscription.</p>';
return;
}
$user_id = get_current_user_id();
$subscriptions = wcs_get_users_subscriptions( $user_id );
if ( empty( $subscriptions ) ) {
echo '<p>You do not have any active subscriptions.</p>';
return;
}
foreach ( $subscriptions as $subscription ) {
if ( $subscription->has_status( array( 'active', 'on-hold' ) ) ) {
$subscription_id = $subscription->get_id();
break;
}
}
if ( isset( $subscription_id ) ) {
echo '<form method="post"><input type="hidden" name="subscription_id" value="' . esc_attr( $subscription_id ) . '" /><button type="submit" name="cancel_subscription" class="button cancel-membership-button">Cancel Subscription</button></form>';
} else {
echo '<p>You do not have any active subscriptions to cancel.</p>';
}
}
add_shortcode( 'cancel_subscription_button', 'cwpai_cancel_user_subscription_button' );
function cwpai_handle_cancel_subscription() {
if ( isset( $_POST['cancel_subscription'] ) && isset( $_POST['subscription_id'] ) ) {
$subscription_id = absint( $_POST['subscription_id'] );
$subscription = wcs_get_subscription( $subscription_id );
if ( $subscription && $subscription->has_status( array( 'active', 'on-hold' ) ) ) {
$subscription->update_status( 'cancelled' );
wc_add_notice( 'Your subscription has been cancelled.', 'success' );
} else {
wc_add_notice( 'Unable to cancel subscription.', 'error' );
}
wp_safe_redirect( wc_get_account_endpoint_url( 'subscriptions' ) );
exit;
}
}
add_action( 'template_redirect', 'cwpai_handle_cancel_subscription' );
@jrglass
Copy link
Author

jrglass commented Aug 23, 2024

Place both code snippets in functions.php or a code snippet plugin.
Edit button text and classes on line 23

Shortcode: [cancel_subscription_button]

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