Jean R.
Jean R.

Reputation: 544

Get the count of all customers with a "billing company" in Woocommerce

I have a website in Wordpress with Woocommerce, and for my reports, I need to know how much professionnal I have.

As Woocommerce doesn't provide this information, I need to get it myself but I can't count manually.

So I decided to use the Woocommerce Rest Api to get the information.

I try to get all customers who fill the "billing company" field.

I make my request with php curl and begin my code like that :

//URL
$url = '<...>/wp-json/wc/v2/customers';

//REQUEST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
$result = curl_exec($ch);
curl_close($ch);  

$json = json_decode($result, true);
print_r($json);

I get two issues :

Any way to do this ?

Thanks

Upvotes: 1

Views: 1170

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253869

Why you dont add a custom sub-tab in WooCommerce > Reports > Customers which name will be "Professionals". In this custom tab you can easily get the customers count that have a billing company.

The code is:

// Add a custom sub-tab to customer tab WooCommerce reports
add_filter( 'woocommerce_admin_reports', 'admin_report_customer_pro_section', 10, 1 );
function admin_report_customer_pro_section( $reports ){
    $reports['customers']['reports']['customer_pro'] = array(
        'title'       => __( 'Professionals', 'woocommerce' ),
        'description' => '',
        'hide_title'  => true,
        'callback'    => 'content_admin_report_customer_pro',
    );
    return $reports;
}

// The content of the customer custom sub-tab
function content_admin_report_customer_pro(){
    // Get all Customers
    $customers = get_users( array( 'role' => 'customer'));
    $count = 0;

    // Iterating through each customer in the array
    foreach ($customers as $customer) {
        // Count professional customers that have a billing company
        if( ! empty( $customer->billing_company ) ) $count++;
    }

    // Output the count
    echo '<div style="background-color:white; padding:8px 20px;"><p>'.__( 'Number of Professionals (with a company): ', 'woocommerce' ) . '<strong style="display:inline-block;background-color:#9c5d90; padding:0 10px; color:white;">' . $count . '</strong></p></div>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works… You will get this:

enter image description here

Upvotes: 2

Related Questions