如何在WooCommerce中重写update_order_review Ajax函数并禁用指定代码?
如何重写WooCommerce的update_order_review AJAX函数并禁用指定代码行
千万别直接修改WooCommerce核心文件里的class-wc-ajax.php,插件更新时你的修改会被完全覆盖。正确的做法是用WordPress钩子机制重写这个AJAX函数,具体操作如下:
操作步骤
- 移除WooCommerce默认注册的
update_order_reviewAJAX动作(覆盖登录用户和游客两种场景) - 注册自定义函数,复制原函数的逻辑但注释掉需要禁用的两行代码
代码实现
将以下代码添加到你的主题functions.php文件或自定义功能插件中:
// 移除默认的update_order_review AJAX动作 add_action( 'init', 'remove_default_order_review_ajax' ); function remove_default_order_review_ajax() { // 移除登录用户的AJAX动作 remove_action( 'wp_ajax_woocommerce_update_order_review', array( 'WC_AJAX', 'update_order_review' ) ); // 移除游客的AJAX动作 remove_action( 'wp_ajax_nopriv_woocommerce_update_order_review', array( 'WC_AJAX', 'update_order_review' ) ); // 注册自定义的AJAX处理函数 add_action( 'wp_ajax_woocommerce_update_order_review', 'custom_woocommerce_update_order_review' ); add_action( 'wp_ajax_nopriv_woocommerce_update_order_review', 'custom_woocommerce_update_order_review' ); } // 自定义的update_order_review处理函数 function custom_woocommerce_update_order_review() { check_ajax_referer( 'update-order-review', 'security' ); if ( ! WC()->cart->is_empty() ) { do_action( 'woocommerce_before_update_order_review' ); // 已禁用以下两行计算代码 // WC()->cart->calculate_shipping(); // WC()->cart->calculate_totals(); // 保留原函数的其余核心逻辑 $response = array( 'result' => 'success', 'messages' => wc_get_notices_html(), 'fragments' => apply_filters( 'woocommerce_update_order_review_fragments', array( '.woocommerce-checkout-review-order-table' => wc_get_template_html( 'checkout/review-order.php' ), '.woocommerce-checkout-payment' => wc_get_template_html( 'checkout/payment.php' ), ) ), ); do_action( 'woocommerce_after_update_order_review' ); wp_send_json( $response ); } wp_send_json( array( 'result' => 'failure', 'messages' => wc_get_notices_html() ) ); }
注意事项
- 若后续WooCommerce更新了原
update_order_review函数的逻辑,你需要同步自定义函数里的对应代码,确保兼容性 - 永远不要直接修改WooCommerce核心文件,所有自定义修改都应通过主题或插件实现
内容的提问来源于stack exchange,提问作者s ss
相关产品推荐
相关产品推荐

