【问题标题】:Creating a custom table of orders in WooCommerce - taking ages to loop through orders在 WooCommerce 中创建自定义订单表 - 循环订单需要很长时间
【发布时间】:2017-08-04 14:10:08
【问题描述】:

我正在我的 WooCommerce 网站上创建一个部分,我的企业客户可以在其中登录并查看他们的哪些员工已下订单。

为了做到这一点,我打算使用 WP_List_Table 来填充一些数据。

但是,由于我们的帖子表和订单库(约 10000 个订单)的大小,我很难创建我的数据数组,循环运行需要很长时间。

这是我创建基本电子邮件地址数组的代码 - 但 Wordpress 在 30 秒后抛出致命错误。

有没有人知道我怎样才能以一种更好的方式做到这一点?非常感谢您的想法。

// Set the parameters for a orders

$customer_orders = get_posts( array(
    'numberposts' => -1,
    'post_type'   => 'shop_order',
    'post_status' => array_keys( wc_get_order_statuses() ),
) );


// Pull a list of order IDs

$orderids = [];
foreach ($customer_orders as $customer_order) {
    $orderids[] = $customer_order->ID;
}

// Create a list of orders
$orders = [];
foreach ($orderids as $orderid) {
    $order = wc_get_order($orderid);
    $order_company = $order->get_billing_company();

    if($order_company = 'Corporate Client Name') {
         $orders[] = $order->get_billing_email();
    }
}

print_r($orders);

【问题讨论】:

    标签: php wordpress foreach woocommerce orders


    【解决方案1】:

    您最好使用自定义 SQL 查询,直接过滤“公司客户名称”计费公司名称。这将避免通过您的 5000 个订单。这是代码:

    // Filtering by a company from the beginning
    $order_company = 'Corporate Client Name';
    
    global $wpdb;
    
    $table_postmeta = $wpdb->prefix . "postmeta";
    
    // 1. First SQL query the order IDs related to 'Corporate Client Name'
    $results = $wpdb->get_col( "
        SELECT post_id
        FROM $table_postmeta
        WHERE $table_postmeta.meta_key LIKE '_billing_company'
        AND $table_postmeta.meta_value = '$order_company'
    " );
    
    // Convert the array of IDs in a coma separated string
    $orders_str = implode(',', $results);
    
    // 2. Second SQL query get the emails from order IDs related to 'Corporate Client Name'
    $emails = $wpdb->get_col( "
        SELECT meta_value
        FROM $table_postmeta
        WHERE $table_postmeta.meta_key LIKE '_billing_email'
        AND $table_postmeta.post_id IN ($orders_str)
    " );
    
    
    // Testing output
    print_r( $emails );
    

    此代码已经过测试并且可以工作

    【讨论】:

    • 你是个绅士洛伊克。我明天去(这里已经很晚了),看看我过得怎么样。谢谢。
    • 嗨 Loic,抱歉回复缓慢。我整个周末都不在电脑前。以上工作非常出色-除了您写!= '$order_company'的地方之外,我以为您的意思是= '$order_company'?非常感谢。这是我第一次涉足 SQL,非常激动人心!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2013-11-02
    相关资源
    最近更新 更多