phpwordpresswoocommercehook-woocommercewoocommerce-subscriptions

WooCommerce Subscription add order note when end date is changed


I try to add an order note on a subscription when the end date is changed. This is my current snippet. It does not add an order note.

I have the info for the values etc. from the official WooCommerce Subscription page: https://woocommerce.com/document/subscriptions/develop/functions/#:~:text=To%20get%20the%20end%20date,%3Eget_time(%20'end'%20)%3B

function add_subscription_note_when_end_date_change($subscription_id){
    $subscription = wc_get_order($subscription_id);
    $old_end_date = substr($end[0],0,10);

    if($_POST['end'] !==null && $old_end_date !== $_POST['end']){
        $note = 'End date changed from '.$old_end_date. ' to ' .$_POST['end'];
        $subscription->add_order_note($note);
    }
}

add_action('woocommerce_process_shop_order_meta','add_subscription_note_when_end_date_change',0);

Solution

  •  function add_subscription_note_when_end_date_change( $subscription_id ) {
            
        // Get the  end date of the subscription
        $old_end_date = $subscription->get_date('end');
        $old_end_date_ymd = explode(' ', $old_end_date);
        $old_end_date_yr = $old_end_date_ymd[0];
    
        $submited_end_date = sanitize_text_field(wp_unslash($_POST['end']));
    
        if (null !== $submited_end_date && $old_end_date_yr !== $submited_end_date) {
    
            $note = 'End date changed from ' . $old_end_date . ' to ' . $submited_end_date;
            $subscription->add_order_note($note);
        }
     }
        
     add_action('woocommerce_process_shop_order_meta', 'add_subscription_note_when_end_date_change', 0);