如何为所有WordPress用户执行wc_update_new_customer_past_orders函数?
问题描述
我希望定期运行一段PHP代码,将WooCommerce访客订单关联到拥有相同邮箱的WordPress用户,尝试为所有用户执行wc_update_new_customer_past_orders函数。我将以下代码设置为一次性执行的PHP代码片段,但未生效:
$users = get_users(); foreach ( $users as $user ) { wc_update_new_customer_past_orders( $user->ID ); }
请问如何为所有WordPress用户执行wc_update_new_customer_past_orders函数?
解决方案
1. 修复代码逻辑并确保正确加载
原代码逻辑本身没问题,但可能因WooCommerce未完成初始化导致失效。可以将代码包裹在WooCommerce初始化钩子中,同时优化内存使用:
add_action( 'woocommerce_init', 'associate_all_users_past_orders' ); function associate_all_users_past_orders() { // 仅管理员可执行,防止误触发 if ( ! current_user_can( 'manage_options' ) ) { return; } // 分批处理用户,避免一次性加载过多导致内存溢出 $paged = 1; $users_per_page = 50; do { $users = get_users( array( 'number' => $users_per_page, 'paged' => $paged, ) ); if ( empty( $users ) ) { break; } foreach ( $users as $user ) { wc_update_new_customer_past_orders( $user->ID ); } $paged++; } while ( true ); // 执行完成后移除钩子,避免重复运行 remove_action( 'woocommerce_init', 'associate_all_users_past_orders' ); }
2. 选择合适的执行方式
方式一:WP CLI(最稳定高效)
如果服务器支持WP CLI,直接在终端运行以下命令,无需修改主题或插件:
wp eval ' $paged = 1; $users_per_page = 50; do { $users = get_users( array( "number" => $users_per_page, "paged" => $paged, ) ); if ( empty( $users ) ) break; foreach ( $users as $user ) { wc_update_new_customer_past_orders( $user->ID ); } $paged++; } while ( true ); '
这种方式不会因页面超时中断执行,适合用户量较大的站点。
方式二:代码片段插件一次性执行
- 安装并激活Code Snippets类插件
- 新建代码片段,粘贴带
woocommerce_init钩子的代码 - 点击“激活”,访问任意前台页面触发执行,完成后可禁用或删除该片段
方式三:设置定期自动执行
如果需要每周/每月自动运行,可通过WordPress定时任务实现:
// 注册定时任务 add_action( 'wp_loaded', 'schedule_associate_orders_task' ); function schedule_associate_orders_task() { if ( ! wp_next_scheduled( 'associate_all_users_past_orders_hook' ) ) { // 每周日凌晨1点执行,可修改为'daily'/'hourly'等周期 wp_schedule_event( time(), 'weekly', 'associate_all_users_past_orders_hook' ); } } // 定时任务回调函数 add_action( 'associate_all_users_past_orders_hook', 'associate_all_users_past_orders' ); function associate_all_users_past_orders() { $paged = 1; $users_per_page = 50; do { $users = get_users( array( 'number' => $users_per_page, 'paged' => $paged, ) ); if ( empty( $users ) ) break; foreach ( $users as $user ) { wc_update_new_customer_past_orders( $user->ID ); } $paged++; } while ( true ); }
注意:若服务器禁用了WP Cron,需设置服务器级定时任务(如Linux Crontab)触发wp-cron.php。
3. 验证执行结果
- 查看用户“我的订单”页面,确认访客订单已显示
- 检查数据库
wp_postmeta表中,订单的_customer_user元字段是否已关联对应用户ID
内容的提问来源于stack exchange,提问作者stephenla
相关产品推荐
相关产品推荐

