【问题标题】:Display the total purchase count of a specific product for customer in Woocommerce在 Woocommerce 中为客户显示特定产品的总购买次数
【发布时间】:2018-10-26 00:10:21
【问题描述】:

在 Woocommerce 中,我想在与当前客户的产品不同的页面上显示特定产品的总数。

所以我尝试从这个线程更改答案代码:
Total purchase count by product for current user in Woocommerce

但我不知道如何设置产品ID,因为该函数使用全局变量产品。

感谢任何帮助

【问题讨论】:

    标签: php wordpress woocommerce count product


    【解决方案1】:

    你只需要对函数做一点改变,比如:

    function wc_product_sold_count( $product_id ) {
        // Only for logged in users
        if ( ! is_user_logged_in() ) return; // Exit for non logged users
    
        $user_id = get_current_user_id(); // Current User 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
    
            // Returned output
            return '<p class="units-bought"><strong>' . $label . ': </strong>' . $units_bought . '</p>';
        }
    }
    
    // The shortcode from this function
    add_shortcode('product_sold_count', 'shortcode_product_sold_count');
    function shortcode_product_sold_count( $atts ) {
        $atts = shortcode_atts( array(
            'id' => '',
        ), $atts, 'product_sold_count' );
    
        return wc_product_sold_count( $atts['id'] );
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。


    用法示例:

    1) 作为 Wordpress 文本编辑器页面中的简码(将 37 替换为您的产品 ID)

    [product_sold_count id="37"]
    

    2) 在任何 php 代码中(将 37 替换为您的产品 ID)

    echo wc_product_sold_count( 37 );
    

    【讨论】:

    • 您确定查询正常吗?示例:在查询中找不到 woim2 作为别名
    猜你喜欢
    • 2017-11-03
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2016-10-01
    • 2020-11-29
    • 2019-08-16
    相关资源
    最近更新 更多