从WordPress快速编辑更新WooCommerce商品描述异常排查
WordPress快速编辑更新post_content无限加载问题修复
问题分析
用wp_update_post更新post_content时触发无限加载,核心原因有两个:
wp_update_post会触发save_post系列钩子,若当前函数挂在这类钩子上,极易引发循环调用,导致前端响应异常- 代码里对
$desc用absint()处理,这会把文本内容强制转为整数,完全不符合post_content的存储逻辑,可能导致更新失败或数据损坏
修复后的代码
function min_max_step_desc_quick_edit_save( $post_id, $post ){ // 验证快速编辑nonce if ( ! wp_verify_nonce( $_POST[ '_inline_edit' ], 'inlineeditnonce' ) ) { return; } // 更新元值 $min = ! empty( $_POST[ 'min' ] ) ? absint( $_POST[ 'min' ] ) : ''; update_post_meta( $post_id, '_alg_wc_pq_min', $min ); $max = ! empty( $_POST[ 'max' ] ) ? absint( $_POST[ 'max' ] ) : ''; update_post_meta( $post_id, '_alg_wc_pq_max', $max ); $step = ! empty( $_POST[ 'step' ] ) ? absint( $_POST[ 'step' ] ) : ''; update_post_meta( $post_id, '_alg_wc_pq_step', $step ); // 处理post_content:用正确的文本过滤函数,禁用钩子避免循环 if ( ! empty( $_POST[ 'desc' ] ) ) { $desc = wp_kses_post( $_POST[ 'desc' ] ); // 需保留HTML用这个,纯文本可替换为sanitize_text_field // 临时移除当前钩子,防止循环调用 remove_action( 'save_post', __FUNCTION__ ); $my_post = array( 'ID' => $post_id, 'post_content' => $desc ); wp_update_post( $my_post ); // 重新添加钩子 add_action( 'save_post', __FUNCTION__, 10, 2 ); } } // 确保钩子优先级与参数配置正确 add_action( 'save_post', 'min_max_step_desc_quick_edit_save', 10, 2 );
关键修复点
- 替换
absint()为wp_kses_post()(或sanitize_text_field()),适配文本内容的处理需求 - 在调用
wp_update_post前后临时移除并恢复当前钩子,阻断循环调用路径 - 增加非空判断,避免空值更新操作
内容的提问来源于stack exchange,提问作者AlexTSF
相关产品推荐
相关产品推荐

