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

如何通过PHP数组获取所有WooCommerce订单的账单/配送邮箱并修复代码问题

问题原因

你当前代码无法累积所有订单邮箱的核心问题是:mailchecker函数内的$life是局部变量,每次函数被订单列渲染逻辑调用时,都会重新初始化为空数组,且函数执行结束后该局部变量就会被销毁,因此每次只能拿到当前正在渲染的订单的邮箱,无法保留之前的结果。

修复方案

方案1:使用静态变量存储累积值(推荐)

静态变量会在函数多次调用之间保留值,不需要额外声明全局作用域,适合仅在该函数内处理累积邮箱的场景,修正代码如下:

add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column',11);
function custom_shop_order_column($columns)
{
    $reordered_columns = array();

    // Woocommerce version 3.3+ compatibility
    $location_after = version_compare( WC_VERSION, '3.3', '<' ) ? 'order_notes' : 'order_status';

    // Inserting the new column in a specific location
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key == $location_after ){
            $reordered_columns['pvdl']= __('PVF/DL', 'woocommerce');
        }
    }
    return $reordered_columns;
}

add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 10, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
    if('pvdl' == $column){
        $order = wc_get_order($post_id);
        $billing_email = $order->get_billing_email();
        mailchecker($billing_email);
        
        // 如需同时收集配送邮箱,放开下方注释即可
        // $shipping_email = $order->get_shipping_email();
        // if(!empty($shipping_email)) mailchecker($shipping_email);
    }
}

function mailchecker($test_mail){
    // 声明静态变量,仅第一次调用时初始化空数组,后续调用保留已有值
    static $life = array();
    array_push($life, $test_mail);
    var_dump($life);
    
    // 如需在外部获取所有累积的邮箱,可添加返回逻辑:return $life;
}

方案2:使用全局变量存储

如果需要在其他函数、其他钩子中也能访问累积的邮箱数组,可以改用全局变量实现:

// 先在函数外部声明全局邮箱数组
$GLOBALS['life_email_array'] = array();

add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column',11);
function custom_shop_order_column($columns)
{
    $reordered_columns = array();

    $location_after = version_compare( WC_VERSION, '3.3', '<' ) ? 'order_notes' : 'order_status';

    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key == $location_after ){
            $reordered_columns['pvdl']= __('PVF/DL', 'woocommerce');
        }
    }
    return $reordered_columns;
}

add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 10, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
    if('pvdl' == $column){
        $order = wc_get_order($post_id);
        $billing_email = $order->get_billing_email();
        mailchecker($billing_email);
    }
}

function mailchecker($test_mail){
    array_push($GLOBALS['life_email_array'], $test_mail);
    var_dump($GLOBALS['life_email_array']);
}

内容的提问来源于stack exchange,提问作者Mustafizur Rahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:06:03