I have WooCommerce with WooCommerce Subscriptions. When users go to the My Account → My Subscriptions page they normally see a full list of all of their subscriptions, active or not.
I would like to change that page to only show subscriptions they have which are a status of ‘active’ or ‘pending-cancel’.
My approach is to modify the query before it is run to put a conditional where status == ‘active’ || ‘pending-cancel’.
I’m stuck. I’ve tried different suggested methods of doing this including hooking into ‘pre_get_posts’, ‘posts_where’, ‘query_vars’
Any ideas of how to do this?
Here’s one example of what I’ve tried, and failed, to get working.
`add_action('pre_get_posts', 'action_pre_get_posts');
function action_pre_get_posts($query) {
if ( is_account_page() && isset( $_GET['view-subscription'] ) && $query->is_main_query() ) {
$query->set( 'post_type', 'shop_subscription' );
$query->set( 'post_status', array( 'wc-active', 'wc-pending-cancel' ) );
}
}`
That was the key that I needed. With that I was able to restrict the my-subscriptions output to just 'active' and 'pending-cancel' by using the following code:
add_filter('wcs_get_users_subscriptions', 'filter_for_active_subscriptions', 10, 2);
function filter_for_active_subscriptions($subscriptions, $user_id) {
$active_subscriptions = array_filter($subscriptions, function($subscription) {
return $subscription->get_status() === 'active' || $subscription->get_status() === 'pending-cancel';
});
return $active_subscriptions;
}
And here's another variant which filters the subscriptions only if the front-end is a woo subscriptions 'My Account' page. Also filters the subscription status using the 'in_array()' function.
add_filter('wcs_get_users_subscriptions', 'filter_for_active_subscriptions', 10, 2);
function filter_for_active_subscriptions($subscriptions, $user_id) {
if( ! is_account_page()) {
return $subscriptions;
}
$active_subscriptions = array_filter($subscriptions, function($subscription) {
return in_array( $subscription->get_status(), ['active', 'pending-cancel', 'on-hold']);
});
return $active_subscriptions;
}