在 WooCommerce 存档和产品页面上显示以文字形式出售的单位

Show units sold as word on WooCommerce Archive and Product Page

我正在尝试了解如何为我的计数显示单个值和多个值。

基本上是这样的:

如何将总销售额转换为 word/string?

这是我正在使用的代码:

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>';
}

哪个有效,但不是我喜欢的方式。有什么建议吗?

对于您的问题,您可以使用 PHP NumberFormatter class,

您还可以使用 WC_Product::get_total_sales()get_post_meta()

所以你得到:

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 );

结果:

  • 到目前为止,已有 31 位客户购买s
  • 到目前为止有一位顾客购买了