php – Woocommerce中当前用户的产品总购买数量

在Woocommerce中,我想在单个产品页面显示当前用户的总购买产品数量.例如,如果约翰买了2次Pen,那么它会在John产品页面中为John用户显示计数(“2”),如果Jack买了5次,那么它将在Jack产品页面中为Jack用户显示5.

我不想要打印总销售数量,我想按照当前登录用户显示.

我在function.PHP文件中的实际代码

add_action( 'woocommerce_single_product_summary', 'wc_product_sold_count', 11 );
function wc_product_sold_count() {
    $get_current_pro_id = $_SESSION["iddd"];

    global $product;
    $current_user = wp_get_current_user();

    if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID,  $product->get_id() )  )
    {

        $units_sold = get_post_meta( $product->id, 'total_sales', true );
//echo '<p>' . sprintf( __( 'Units Sold: %s', 'woocommerce' ), $units_sold ) . '</p>';

        return $units_sold;
    }
}

解决方法:

钩子函数中使用非常轻的SQL查询可以轻松完成:

add_action( 'woocommerce_single_product_summary', 'wc_product_sold_count', 11 );
function wc_product_sold_count() {
    // Only for logged in users
    if ( ! is_user_logged_in() ) return; // Exit for non logged users

    global $wpdb, $product;

    $user_id = get_current_user_id(); // Current User ID
    $product_id = $product->get_id(); // Current Product ID

    // The sql request
    $units_bought = $wpdb->get_var( "
        SELECT SUM(woim2.Meta_value)
        FROM {$wpdb->prefix}woocommerce_order_items AS woi
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemMeta woim ON woi.order_item_id = woim.order_item_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemMeta woim2 ON woi.order_item_id = woim2.order_item_id
        INNER JOIN {$wpdb->prefix}postMeta pm ON woi.order_id = pm.post_id
        INNER JOIN {$wpdb->prefix}posts AS p ON woi.order_id = p.ID
        WHERE woi.order_item_type LIKE 'line_item'
        AND p.post_type LIKE 'shop_order'
        AND p.post_status IN ('wc-completed','wc-processing')
        AND pm.Meta_key = '_customer_user'
        AND pm.Meta_value = '$user_id'
        AND woim.Meta_key = '_product_id'
        AND woim.Meta_value = '$product_id'
        AND woim2.Meta_key = '_qty'
    ");

    // display count if is greater than zero
    if( $units_bought > 0 ){
        $label = __( 'Units bought' , 'woocommerce' ); // Label

        // Output
        echo '<p class="units-bought"><strong>' . $label . ': </strong>' . $units_bought . '</p>';
    }
}

代码位于活动子主题(或活动主题)的function.PHP文件中.经过测试和工作.

enter image description here

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...