You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取WooCommerce客户历史支付方式并导出为CSV文件?

WooCommerce 获取客户历史支付方式并导出CSV入门指引

一、代码放置位置

1. 自定义插件(推荐)

这种方式不会因主题更新丢失代码,步骤如下:

  • 在wp-content/plugins/目录下新建文件夹wc-payment-export
  • 新建文件wc-payment-export.php,开头添加插件标识代码:
<?php
/*
Plugin Name: WooCommerce 支付方式导出工具
Description: 导出客户历史订单支付方式为CSV
Version: 1.0
Author: 自定义名称
*/

后续核心逻辑代码都写在这个文件里。

2. 主题functions.php文件

如果只是临时测试,可将代码添加到当前主题的functions.php文件末尾,但注意主题更新会覆盖此代码,不建议长期使用。

二、完整导出CSV代码示例

将以下代码放到上述插件文件或functions.php中:

// 添加后台菜单入口
add_action('admin_menu', 'wc_payment_export_menu');
function wc_payment_export_menu() {
    add_menu_page(
        '支付方式导出',
        '支付方式导出',
        'manage_woocommerce',
        'wc-payment-export',
        'wc_payment_export_callback'
    );
}

// 导出回调函数
function wc_payment_export_callback() {
    // 权限校验
    if (!current_user_can('manage_woocommerce')) {
        wp_die('无权限访问');
    }

    // 触发导出操作
    if (isset($_GET['export'])) {
        // 设置CSV表头
        $headers = array('订单ID', '客户邮箱', '支付方式', '订单日期');
        $filename = 'customer-payment-methods-' . date('Ymd') . '.csv';

        // 输出CSV响应头部
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Pragma: no-cache');
        header('Expires: 0');

        // 打开输出流
        $output = fopen('php://output', 'w');
        fputcsv($output, $headers);

        // 查询目标订单(默认仅已完成状态,可按需调整)
        $orders = wc_get_orders(array(
            'status' => 'completed',
            'limit' => -1, // -1表示获取所有订单
            'orderby' => 'date',
            'order' => 'DESC'
        ));

        // 遍历订单写入CSV
        foreach ($orders as $order) {
            $order_id = $order->get_id();
            $customer_email = $order->get_billing_email();
            $payment_method = $order->get_payment_method_title();
            $order_date = $order->get_date_created()->format('Y-m-d H:i:s');

            fputcsv($output, array($order_id, $customer_email, $payment_method, $order_date));
        }

        fclose($output);
        exit;
    }

    // 导出按钮页面
    echo '<div class="wrap">';
    echo '<h1>导出客户历史支付方式</h1>';
    echo '<p><a href="?page=wc-payment-export&export=1" class="button button-primary">导出CSV</a></p>';
    echo '</div>';
}

三、使用步骤

  • 若用自定义插件:在WordPress后台插件列表中启用「WooCommerce 支付方式导出工具」
  • 启用后,后台左侧菜单会出现「支付方式导出」入口,点击进入后,点击「导出CSV」按钮即可下载文件
  • 下载的CSV文件可直接用Excel、Numbers等电子表格软件打开编辑

四、调整说明

  • 如需导出其他状态订单,修改wc_get_orders中的status参数,比如改为array('completed', 'processing')即可同时导出已完成和处理中的订单
  • 订单量极大时,可先将limit设为10做测试,确认无误后再改为-1导出全部,同时可能需要调整PHP执行时间避免超时

内容的提问来源于stack exchange,提问作者Kirk Salisbury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:35:10