WordPress中如何在post_updated触发后运行生成WooCommerce产品XML的PHP脚本
代码调整方案
你可以按照以下逻辑修改现有代码,实现仅在WooCommerce产品更新时触发XML生成脚本:
完整可直接使用的代码
function check_values( $post_ID, $post_after, $post_before ){ // 过滤非产品类型的更新请求 if ( get_post_type( $post_ID ) !== 'product' ) { return; } // 过滤自动保存、修订版本、自动草稿等非用户主动更新的场景 if ( wp_is_post_autosave( $post_ID ) || wp_is_post_revision( $post_ID ) || get_post_status( $post_ID ) === 'auto-draft' ) { return; } // 【可选配置】仅在产品核心字段(比如价格)变更时触发,不需要可以删除该段 $regular_price_before = get_post_meta( $post_before->ID, '_regular_price', true ); $regular_price_after = get_post_meta( $post_after->ID, '_regular_price', true ); $sale_price_before = get_post_meta( $post_before->ID, '_sale_price', true ); $sale_price_after = get_post_meta( $post_after->ID, '_sale_price', true ); // 打开下方注释即可实现仅价格变动时才生成XML // if ( $regular_price_before === $regular_price_after && $sale_price_before === $sale_price_after ) { // return; // } // 调用你的XML生成逻辑,二选一即可 // 方式1:引入独立的XML生成脚本,替换为你实际的脚本路径 require_once( WP_CONTENT_DIR . '/your-custom-xml-generator.php' ); // 方式2:如果XML生成逻辑已经封装为函数,直接调用对应函数 // your_generate_product_xml_func(); } add_action( 'post_updated', 'check_values', 10, 3 );
注意事项
- 路径替换:
require_once中填写的路径请替换为你实际存放XML生成脚本的绝对路径,使用WP_CONTENT_DIR(对应站点wp-content目录的绝对路径)可避免相对路径写错的问题 - 高耗时场景优化:如果你的站点产品数量较多,XML生成耗时超过3秒,建议改为异步调度执行,避免拖慢后台产品保存的响应速度,调整逻辑如下:
- 先注册自定义异步执行钩子
add_action( 'async_generate_product_xml', 'async_run_xml_generator' ); function async_run_xml_generator() { require_once( WP_CONTENT_DIR . '/your-custom-xml-generator.php' ); }- 将原有代码中直接调用脚本的部分替换为调度单次异步任务
// 避免重复调度相同任务 if ( ! wp_next_scheduled( 'async_generate_product_xml' ) ) { wp_schedule_single_event( time(), 'async_generate_product_xml' ); }
内容的提问来源于stack exchange,提问作者CJabber201
相关产品推荐
相关产品推荐

