我正在使用 Woocommerce CSV Export 插件。
我希望有一种方法来检查客户是否是新客户,如果是,则为 自定义 meta-key
编写订单元数据一个true
值。
但如果用户不是新用户,则不会发生任何事情。
我想首先从 WP 用户(user_registered)的创建日期开始。但我认为有更好更快的方法。换句话说,我怎么知道这是否是客户的第一笔订单...
我的目标:如果该客户是第一次订购,请获得 TRUE
导出 CSV 中此订单的值。
然后我尝试过to use this answer code没有成功。
我的问题:
我怎样才能实现这个目标?
谢谢
最佳答案
基于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 文件中。
感谢钩子(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 文件中。
Now only for the FIRST new customer order you will have a custom meta data which 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;
所有代码都经过测试并且可以工作。
引用文献
关于php - 为 WooCommerce CSV 导出插件添加自定义字段 - 对于客户首次订单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38984460/