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 按鈕旁邊,如下圖所示
現在,我希望把這個價格變化放到標題正下方的價格那裏,即替換"From: £35 £30 ",並隱藏 add to cart 旁邊的那個價格,變成下面這樣
所用到的代碼如下:
/** * 利用 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 事件