如果用户已经在Woocommerce中购买了当前产品,则显示自定义文本

时间:2018-10-29 15:08:59

标签: php sql wordpress woocommerce product

在woocommerce中,当客户已经购买了当前产品时,我使用wc_customer_bought_product()函数在单个产品页面中显示自定义文本消息。但我想检查购买的产品是否处于“已完成”状态的订单上。

除非满足以下条件,否则不应该显示该消息:

1)用户已登录 2)用户购买了产品 3)当前产品的至少一个下订单已设置为完成(我不知道该如何完成)。

这是我的代码:

add_action( 'woocommerce_before_single_product_summary', 'woo_review_discount_message');
function woo_review_discount_message() {
    if ( is_user_logged_in() ) {
        global $product;

        $current_user = wp_get_current_user();

        if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->get_id() && $order->status->complete ) ) 
            echo '<div class="user-bought"><span style="color:#CA364D;font-weight:bold;font-size:18px;"><i class="wishlist-icon icon-heart-o"></i></span> Hi ' . $current_user->first_name . '! Please write a review below.</a></div>';
    }
}

我尝试添加&& $order->status->complete,但这没用。

我们非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

如果要定位具有完整状态的仅订单,则可以使用基于wc_customer_bought_product() source code的以下自定义条件函数:

RequestClass

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

如果客户未登录,则不会显示任何内容。

  

像Woocommerce功能// Utility function to check if a customer has bought a product (Order with "completed" status only) function customer_has_bought_product( $product_id, $user_id = 0 ) { global $wpdb; $customer_id = $user_id == 0 || $user_id == '' ? get_current_user_id() : $user_id; $status = 'wc-completed'; if( ! $customer_id ) return false; // Count the number of products $count = $wpdb->get_var( " SELECT COUNT(woim.meta_value) FROM {$wpdb->prefix}posts AS p INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id WHERE p.post_status = '$status' AND pm.meta_key = '_customer_user' AND pm.meta_value = $customer_id AND woim.meta_key IN ('_product_id','_variation_id') AND woim.meta_value = $product_id " ); // Return a boolean value if count is higher than 0 return $count > 0 ? true : false; } add_action( 'woocommerce_before_single_product_summary', 'woo_review_discount_message'); function woo_review_discount_message() { global $product; if ( customer_has_bought_product( $product->get_id() ) && ! $product->is_type('variable') ) { $user = wp_get_current_user(); echo '<div class="user-bought"><span style="color:#CA364D;font-weight:bold;font-size:18px;"><i class="wishlist-icon icon-heart-o"></i></span> Hi ' . $user->first_name . '! Please write a review below.</a></div>'; } } 一样,该功能不适用于可变产品的单个页面。