WooCommerce 有丰富的 javascript 脚本,你可知这些脚本中也留有像 php hooks 一样的自定义事件呢?利用这些 custom javascript event,修改 js 脚本变得容易了。

不得不知的 jQuery.trigger()

jQuery 的 trigger() 是一种用代码激活事件的方法,可以是预定义的事件,例如 click,submit 等,也可以是自定义事件。这些自定义事件标志着某些事件的发生,之后用 bind 方法将一些功能绑定到这个事件上,就可以确保脚本的执行顺序,做定制化修改。

WooCommerce 中的 Custom Event

WooCommerce 的前台脚本在 WooCommerce/assets/js/frontend 目录下,带有 min 的是真实使用的脚本,不带 min 的是源代码版。打开源代码版,搜索.trigger 就可以找到自定义事件。

例如在 add-to-cart-variation.js 文件中可以找到

// Custom event for when variations have been updated
$variation_form.trigger('WooCommerce_update_variation_values');

再往下看,还有 show_variation 事件,看名字就知道这是显示产品属性的标志性事件。

$single_variation_wrap.slideDown('200')
.trigger( 'show_variation', [ variation ] );

下面就用 show_variation 事件演示一下 WooCommerce Custom Event 的使用方法。

代码示例:改变产品属性价格的显示位置

在带有属性的产品页面,修改产品属性时,价格变化显示在 add to cart 按钮旁边,如下图所示

product-variation-1

现在,我希望把这个价格变化放到标题正下方的价格那里,即替换”From: £35 £30 “,并隐藏 add to cart 旁边的那个价格,变成下面这样

product-variation-2

所用到的代码如下:

/**
 * 利用 jquery custom event 修改价格
 *
 * 用 is_product() 确保脚本只在产品页加载
 * 用 action: wp_footer 将脚本加载到 footer 区域
 */
 function theme_custom_wc_script(){
	if( !is_product() ) return;
?>
<script type="text/javascript">
  jQuery( document ).bind( 'show_variation', function() {
	var price = jQuery( '.single_variation .price' ).html();
	jQuery( '.single_variation' ).hide();
	jQuery( '.entry-summary .price' ).html( price );
  } );
</script>
<?php
}
add_action( 'wp_footer', 'theme_custom_wc_script' );

注意代码中用 bind 方法绑定了 show_variation 时间,跟绑定 click 等事件没有差别。

扩展阅读

另一个使用 custom event 的示例:Add ‘Sold Out’ to WooCommerce Variable Product Dropdown,
使用了 WooCommerce_update_variation_values 事件