Total purchase count by product for current user in Woocommerce
在 Woocommerce 中,我想在单个产品页面中显示当前用户的总购买产品数。例如,如果 John 购买了 2 次 Pen,那么它会在此产品页面中为 John 用户显示计数("2"),如果 Jack 购买了 5 次,那么它会在此产品页面中为 Jack 用户显示 5。<铅>
我不想打印总销售量,我想按当前登录用户显示。
我在function.php文件中的实际代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 查询轻松完成:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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">' . $label . ': ' . $units_bought . '</p>'; } } |
代码进入您的活动子主题(或活动主题)的function.php 文件中。经测试且有效。
相关:在 Woocommerce 中为客户显示特定产品的总购买次数