更新日期:2023-05-18

如果你的商店頁面裡面,摻雜有簡單商品、可變商品,或是組合商品時,你會看到不同名稱的按鈕,像是「加入購物車」、「選擇規格」、「查看商品」,若是沒有價格的商品,則會顯示「查看內容」。不同按鈕有不同的效果,這樣子的體驗其實不怎麼好,也沒有一致性,底下教你如何都改為點擊按鈕後都進入商品介紹頁面去。

更改的方式有很多種,像是直接修改 Woocommerce 的 template 內容,他的檔案是 「woocommerce/templates/loop/add-too-cart.php」。可將這隻檔案依照 Woocommerce 要求放置的方式複製到你的佈景下,然後自行修改按鈕內容。

另一種方法是用 hook 來修改,將修改的程式碼寫在佈景主題的 functions.php 內。或是寫在可以讓你寫程式碼的外掛內,例如 Code Snippets ,這樣子一來就算換佈景,也不用再改一次,Code Snippet 是我最推薦的作法。程式碼如下:

add_filter( 'woocommerce_loop_add_to_cart_link', function($add_to_cart_html, $product, $args){
	
	if( 'external' === $product->get_type() ) return $add_to_cart_html;  //不改外部商品的按鈕
	
	return sprintf(
		'<a href="%s" data-quantity="%s" class="%s" %s>%s</a>',
		esc_url( $product->get_permalink() ),
		esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ),		
		'button', //按鈕外觀樣式,依照需求自行修改 class 名稱 
		isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '',
		__( 'Read more', 'woocommerce' ) 
	);
	
}, 10, 3 );