Search code examples
phpwordpresswoocommerceaccountwoocommerce-subscriptions

Gateway between Woocommerce Subscriptions and Account Funds plugins


I have purchased 2 plugins (Woocommerce Subscriptions and Account Funds) that state in their relevant docs that they are compatible with each other. I wish to make a Simple Subscription product that adds the product price as account funds for that user when checked out and again each time the Simple Subscription product renews.

The code below has been pasted into at the bottom of the functions.php file in my theme but doesn't seem to update the account funds when a subscription is purchased.

add_action('processed_subscription_payment', 'custom_process_order', 10, 2);

function custom_process_order($user_id, $subscription_key) {

    // split subscription key into order and product IDs
    $pieces = explode( '_', $subscription_key);
    $order_id = $pieces[0];
    $product_id = $pieces[1];

    // get order total
    $order = wc_get_order( $order_id );
    $amount = $order->get_total();

    // get current user's funds
    $funds = get_user_meta( $user_id, 'account_funds', true );
    $funds = $funds ? $funds : 0;
    $funds += floatval( $amount );

    // add funds to user
    update_user_meta( $user_id, 'account_funds', $funds );

}

Can anyone help me get this working? As the code above is from a great Stack Overflow post, but that post is around 2 years old, therefore various Woocommerce settings may have changed since - being the possible reason why it doesn't work at present.


Solution

  • The hook that you are using doesn't seem to exist anymore. Try the following simpler code instead:

    add_action('woocommerce_subscription_payment_complete', 'action_subscription_payment_complete_callback', 10, 1);
    function action_subscription_payment_complete_callback( $subscription ) {
        // Get the instance WC_Order Object for the current subscription
        $order = wc_get_order( $subscription->get_parent_id() );
    
        $user_id = (int) $order->get_customer_id(); // Customer ID
        $total   = (float) $order->get_total(); // Order total amount
    
        // Get customer existing funds (zero value if no funds found)
        $user_funds = (float) get_user_meta( $user_id, 'account_funds', true );
    
        // Add the order total amount to customer existing funds
        update_user_meta( $user_id, 'account_funds', $funds + $total );
    }
    

    Code goes on function.php file of your active child theme (or active theme). It should works.