Search code examples
phpwordpresswoocommercesubscriptionwoocommerce-subscriptions

How Can I Properly Use WooCommerce Subscriptions API in PHP?


Documentation is very scarce. I'm trying to create some code that uses WooCommerce subscriptions (a plugin for WooCommerce) API to get a list of subscriptions and all of the details of each subscription. The docs and examples out there are just so scarce and weak I can't get it right. The following code didn't produce any errors but isn't outputting any subscriptions (just a blank page). How can I list all the details of all the subscriptions?

<?php

if(isset($_REQUEST['Action']))
{
    $Action = $_REQUEST['Action'];
    switch($Action)
    {
        case "ValidateSubscription":
            chdir("../wp-content/plugins/woocommerce-subscriptions/classes");
            include '../../woocommerce/woocommerce.php';
            //include '../woo-includes/woo-functions.php';
            //include '../woo-includes/class-wc-dependencies.php';
            include 'class-wc-subscriptions-manager.php';

            $Subscriptions = WC_Subscriptions_Manager::get_all_users_subscriptions();
            print_r($Subscriptions);
            break;
        default:
            echo "invalid action";
    }
}else
{
    echo "no action specified";
}

Solution

  • That is not how you include WordPress functions in external code. Try this.

    if(isset($_REQUEST['Action']))
    {
        $Action = $_REQUEST['Action'];
        switch($Action)
        {
            case "ValidateSubscription":
    
                include('../wp-load.php'); //Guessing this path based on your code sample... should be wp root
    
                $Subscriptions = WC_Subscriptions_Manager::get_all_users_subscriptions();
                print_r($Subscriptions);
                break;
            default:
                echo "invalid action";
        }
    }else
    {
        echo "no action specified";
    }