Search code examples
functionwoocommercehook-woocommercewoocommerce-subscriptions

Woocommerce Subscriptions update next payment date from functions.php


I would like to change the next payment date of active subscriptions after the Initial (first) Subscription payment is completed after the trial period.

        <?php   global $woocommerce;
        $all_meta_for_user = get_user_meta( 53 );
                    $order = new WC_Order(4843);
        $order_id=4846;//PUT YOUR ORDER ID HERE
                    $subscription    = wcs_get_subscription( 4846 );
        add_action('woocommerce_subscription_payment_complete', 'nextpaymentdatechange', 10, 1);  

        function nextpaymentdatechange($order_id){
        if (WC_Subscriptions_Order::order_contains_subscription($order_id)) {

            $nextdate = get_post_meta( $order_id, '_schedule_next_payment', true );
            $threedays_ago = date('Y-m-d H:i:s', strtotime('-15 days', strtotime($nextdate)));
            update_post_meta($order_id , '_schedule_next_payment', $threedays_ago);
        }
        } ?>

Solution

  • I got a solution for the subscription-related question which posted. It may help others.

    function pro_subscription($subscription){
    $sid = $subscription->id;
    $uid = $subscription->customer_user;
    $subscription    = wcs_get_subscription( $sid );
    $items = $subscription->get_items();    
    foreach ( $items as $item ) {
        $product_id = $item->get_product_id();
        $order_id = $subscription->get_parent_id();
    }
    $subscription_key = WC_Subscriptions_Manager::get_subscription_key( $order_id, $product_id);
    
    $td = new DateTime($subscription->get_date( 'trial_end_date' ));
    $try_date = $td->format('Y-m-d');
    
    $sd = new DateTime($subscription->get_date( 'next_payment_date' ));
    $pay_date = $sd->format('Y-m-d');
    
    $sdt = new DateTime($subscription->get_date( 'start_date' ));
    $sst = $sd->format('Y-m-d H:i:s');  
    $tst = $td->format('Y-m-d H:i:s');
    
    $date1=date_create($tst);
    $date2=date_create($sst);
    $diff=date_diff($date1,$date2);
    $df = 30 - $diff->format("%a");
    
    $next_pay = date('Y-m-d H:i:s', strtotime($ts. ' + ' . $df . ' days'));
    
    if($try_date == $pay_date){
        WC_Subscriptions_Manager::set_next_payment_date( $subscription_key, $uid, $next_pay );  
    }
     }