WordPress-woo添加自定义监听事件

注册js文件

wp-content\themes\xshen\incwoocommerce.php

// wp-content\themes\xshen\incwoocommerce.php
function register_custom_script() {
    // 注册脚本
    wp_register_script(
        'add-to-cart-custom', // 脚本句柄,用于引用该脚本
        get_stylesheet_directory_uri() . '/js/shop/add-to-cart-custom.js', // JS 文件路径
        array( 'jquery', 'wc-add-to-cart-variation' ), // 依赖项,这里依赖 jQuery
        filemtime(get_template_directory().'/js/shop/add-to-cart-custom.js'), // 版本号
        true // 是否在页脚加载
    );

}
add_action( 'wp_enqueue_scripts', 'register_custom_script' );

在合适的地方加载js文件

wp-content\themes\xshen\woocommerce\content-single-product.php

/**
 * Hook: woocommerce_single_product_summary.
 *
 * @hooked woocommerce_template_single_title - 5
 * @hooked woocommerce_template_single_rating - 10
 * @hooked woocommerce_template_single_price - 10
 * @hooked woocommerce_template_single_excerpt - 20
 * @hooked woocommerce_template_single_add_to_cart - 30
 * @hooked woocommerce_template_single_meta - 40
 * @hooked woocommerce_template_single_sharing - 50
 * @hooked WC_Structured_Data::generate_product_data() - 60
 */
if ( ! function_exists( 'add_to_cart_custom' ) ) {
    function add_to_cart_custom(){
        wp_enqueue_script( 'add-to-cart-custom' );
    }
}
add_action('woocommerce_single_product_summary','add_to_cart_custom',31);
do_action( 'woocommerce_single_product_summary' );
defined( 'ABSPATH' ) || exit;