基于这个答案代码 https://stackoverflow.com/questions/38874189/checking-if-customer-has-already-bought-something-in-woocommerce/38875458#38875458 (我最近做了),可以有一个函数在数据库中添加元键/值wp_postmeta
新客户优先订单表。所以我们将这样改变一下条件函数:
function new_customer_has_bought() {
$count = 0;
$new_customer = false;
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id()
) );
// Going through each current customer orders
foreach ( $customer_orders as $customer_order ) {
$count++;
}
// return "true" when it is the first order for this customer
if ( $count > 2 ) // or ( $count == 1 )
$new_customer = true;
return $new_customer;
}
此代码位于活动子主题或主题的 function.php 文件中,或插件 php 文件中。
谢谢钩子中的用法:
add_action( 'woocommerce_thankyou', 'tracking_new_customer' );
function tracking_new_customer( $order_id ) {
// Exit if no Order ID
if ( ! $order_id ) {
return;
}
// The paid orders are changed to "completed" status
$order = wc_get_order( $order_id );
$order->update_status( 'completed' );
// For 1st 'completed' costumer paid order status
if ( new_customer_has_bought() && $order->has_status( 'completed' ) )
{
// Create 'first_order' custom field with 'true' value
update_post_meta( $order_id, 'first_order', 'true' ); needed)
}
else // For all other customer paid orders
{
// udpdate existing 'first_order' CF to '' value (empty)
update_post_meta( $order_id, 'first_order', '' );
}
}
此代码位于活动子主题或主题的 function.php 文件中,或插件 php 文件中。
Now only为了第一个新客户订单您将拥有一个自定义元数据key is '_first_customer_order'
and value is true.
为了得到这个值对于定义的订单 ID,您将使用它(最后一个参数意味着它是一个字符串):
// Getting the value for a defined $order_id
$first_customer_order = get_post_meta( $order_id, 'first_order', false );
// to display it
echo $first_customer_order;
所有代码都经过测试并且可以工作。
参考
- 模板结构 + 通过主题覆盖模板 https://docs.woocommerce.com/document/template-structure/
- 检查客户是否已经在 WooCommerce 中购买了商品 https://stackoverflow.com/questions/38874189/checking-if-customer-has-already-bought-something-in-woocommerce/38875458#38875458
- 检查客户是否之前在 WooCommerce 中购买过特定产品 https://stackoverflow.com/questions/38769888/check-if-a-customer-has-purchased-a-specific-product-earlier-in-woocommerce/38772202#38772202
- WP 代码参考 - update_post_meta() 函数 https://developer.wordpress.org/reference/functions/update_post_meta/
- WP 代码参考 - get_post_meta() 函数 https://developer.wordpress.org/reference/functions/get_post_meta/