I am trying to understand how to show single and multiple values for my count.
Basically like this:
How can I convert the total sales number to a word/string?
This is the code I am working with:
add_action( 'woocommerce_single_product_summary', 'product_sold_count', 11 );
add_action( 'woocommerce_after_shop_loop_item', 'product_sold_count', 11 );
function product_sold_count() {
global $product;
$units_sold = get_post_meta( $product->get_id(), 'total_sales', true );
if ($units_sold) echo '<span class="bought-by-customers">' . sprintf( __( 'Bought by %s customers so far', 'woocommerce' ), $units_sold ) . '</span>';
}
Which works, but not the way I prefer it. Any advice?
For your question you can use the PHP NumberFormatter class,
You can also use WC_Product::get_total_sales()
versus get_post_meta()
So you get:
function product_sold_count() {
global $product;
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Get total sales
$units_sold = $product->get_total_sales();
if ( $units_sold >= 1 ) {
// https://www.php.net/manual/en/class.numberformatter.php
$fmt = new NumberFormatter( 'en', NumberFormatter::SPELLOUT );
// Singular are plural
$units_sold == 1 ? $s_p = '' : $s_p = 's';
// Output
echo '<span class="bought-by-customers">' . sprintf( __( 'Bought by %s customer%s so far', 'woocommerce' ), $fmt->format( $units_sold ), $s_p ) . '</span>';
}
}
}
add_action( 'woocommerce_single_product_summary', 'product_sold_count', 11 );
add_action( 'woocommerce_after_shop_loop_item', 'product_sold_count', 11 );
Result: