WordPress注册调用profile_update钩子引发内存耗尽错误
解决WordPress中profile_update钩子导致的内存耗尽错误
你的代码出现内存耗尽的核心原因是无限循环:在profile_update钩子的回调函数my_profile_update中调用了wp_update_user(),而这个函数执行时会再次触发profile_update钩子,导致函数反复被调用,不断消耗服务器内存直至耗尽。
修复方案一:临时移除钩子避免循环
在执行用户更新操作前,临时移除当前钩子,完成更新后再重新添加:
add_action( 'profile_update', 'my_profile_update', 10, 2 ); function my_profile_update( $user_id, $old_user_data ) { if (isset($_POST['user_url'])) { // 临时移除钩子,阻止循环触发 remove_action( 'profile_update', 'my_profile_update', 10 ); // 执行用户URL更新 wp_update_user( array( 'ID' => $user_id, 'user_url' => sanitize_text_field($_POST['user_url']) ) ); // 重新添加钩子,恢复原有功能 add_action( 'profile_update', 'my_profile_update', 10, 2 ); } }
修复方案二:对比数据仅在变化时更新
通过对比新旧用户数据,只在user_url确实发生变化时执行更新操作,从根源避免无效循环:
add_action( 'profile_update', 'my_profile_update', 10, 2 ); function my_profile_update( $user_id, $old_user_data ) { if (isset($_POST['user_url'])) { $new_user_url = sanitize_text_field($_POST['user_url']); // 仅当新URL与旧数据不同时才执行更新 if ( $old_user_data->user_url !== $new_user_url ) { wp_update_user( array( 'ID' => $user_id, 'user_url' => $new_user_url ) ); } } }
额外优化建议
如果你的需求是在用户注册时同步处理user_url字段,完全可以直接在已有的save_data函数中处理,无需依赖profile_update钩子,这样更高效:
function save_data($customer_id) { if (isset($_POST['billing_first_name'])) { update_user_meta($customer_id, 'first_name', sanitize_text_field($_POST['billing_first_name'])); update_user_meta($customer_id, 'billing_first_name', sanitize_text_field($_POST['billing_first_name'])); } // 直接在注册保存流程中处理user_url if (isset($_POST['user_url'])) { wp_update_user( array( 'ID' => $customer_id, 'user_url' => sanitize_text_field($_POST['user_url']) ) ); } }
内容的提问来源于stack exchange,提问作者user2015172
相关产品推荐
相关产品推荐

