<?php
function set_subscriptions_to_first_of_month($subscription, $order, $recurring_cart){
$isMembership = false;
foreach($subscription->get_items() as $item){
if(has_term('membership', 'product_cat', $item['product_id'])){ // Subscription was purchased from a membership product
$isMembership = true;
}
}
if($isMembership){
$subscription_start = strtotime($subscription->schedule_start);
// Number of days in the current month
$number_of_days = date('t', mktime(0, 0, 0, date('m', $subscription_start), 1, date('Y', $subscription_start)));
// Day will always be the first of the month
$date_day = 1;
// If current day is less than halfway through the month expiry is set to first of same month
if(date('d', $subscription_start) <= $number_of_days / 2){
$date_month = date('m', $subscription_start);
$date_year = date('Y', $subscription_start) + 1;
}else{ // otherwise set to the first of the following month
// set next month to january if the current month is december
if(date('m', $subscription_start) >= 12){
$date_month = 1;
$date_year = date('Y', $subscription_start) + 2;
}else{
$date_month = date('m', $subscription_start) + 1;
$date_year = date('Y', $subscription_start) + 1;
}
}
$new_date_next = date('Y-m-d h:i:sa', mktime(0, 0, 0, $date_month, $date_day, $date_year));
$new_date_end = date('Y-m-d h:i:sa', mktime(0, 1, 0, $date_month, $date_day, $date_year));
$new_dates = array(
'next_payment' => $new_date_next,
'end' => $new_date_end
);
$subscription->update_dates($new_dates, 'America/New_York');
}
}
add_action('woocommerce_checkout_subscription_created', 'set_subscriptions_to_first_of_month', 10, 3);