【问题标题】:Add custom field for WooCommerce CSV Export plugin - For customer first order [closed]为 WooCommerce CSV 导出插件添加自定义字段 - 对于客户的第一笔订单 [关闭]
【发布时间】:2016-12-23 09:25:54
【问题描述】:

我正在使用 Woocommerce CSV 导出 插件。 我想有一种方法来检查客户是否是新客户,如果是,按顺序写入 custom meta-keytrue 的元数据。
但是如果用户不是新用户,什么都不会发生。

我想首先从 WP 用户 (user_registered) 的创建日期开始。但我认为有更好更快的方法。也就是说,我怎么知道这是不是客户的第一单……

我的目标:如果此客户是第一次订购,请在导出 CSV 中为此订单设置 TRUE 值。

然后我尝试to use this answer code没有成功。

我的问题:
我怎样才能做到这一点?

谢谢

【问题讨论】:

  • 欢迎来到 SO! SO 不是“我需要这个;给我代码”服务。有搜索引擎。请提供一些您已经尝试过/遇到问题的代码以获得答案。

标签: php wordpress plugins woocommerce orders


【解决方案1】:

基于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> 并且 valuetrue

要为定义的订单 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;

所有代码都经过测试并且可以运行。


参考文献

【讨论】:

  • 我明天会测试一下。谢谢分享。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 2016-10-12
  • 2020-12-30
相关资源
最近更新 更多