基于this answer code(我最近做了),可以有一个函数在数据库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 文件中。
THANKYOU HOOK 中的用法:
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 文件中。
现在仅对于第一个新客户订单,您将拥有一个自定义元数据,key 是 '_first_customer_order' strong> 并且 value 为 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;
所有代码都经过测试并且可以运行。
参考文献