本文整理了一些適用於 WooCommerce 的短代碼,方便查閲和使用,更是為了理清思路,提高自己。以下 WooCommerce 簡稱 WC,代碼放在主題的 functions.php 中即可。

在主題中聲明對 WooCommerce 的支持

add_action( 'after_setup_theme', 'WooCommerce_support' );
function WooCommerce_support() {
	add_theme_support( 'WooCommerce' );
}

禁用 WooCommerce 默認樣式

// Disable WooCommerce styles
add_filter( 'WooCommerce_enqueue_styles', '__return_false' );

官方文檔鏈接

禁用默認樣式,就要引入自己的樣式,可以直接寫在 style.css 中,也可以另外寫一個樣式表

function wp_enqueue_WooCommerce_style(){
	wp_register_style( 'WooCommerce', get_template_directory_uri() . '/css/WooCommerce.css' );
	if ( class_exists( 'WooCommerce' ) ) {
		wp_enqueue_style( 'WooCommerce' );
	}
}
add_action( 'wp_enqueue_scripts', 'wp_enqueue_WooCommerce_style' );

如果樣式表中用到了 WooCommerce 默認的圖片,還應將 WooCommerce/assets/images 文件夾下的圖片拷貝到主題目錄。

WC 麪包屑導航

修改麪包屑導航位置

首先刪除默認的麪包屑導航

remove_action( 'WooCommerce_before_main_content', 'WooCommerce_breadcrumb', 20, 0);

將導航添加到其它位置,例如放在 header.php 中,則直接在 header.php 適當位置插入如下代碼

if( function_exists( 'WooCommerce_breadcrumb') ) WooCommerce_breadcrumb();

也可以用 add_action 添加,例如

add_action( 'WooCommerce_after_main_content', 'WooCommerce_breadcrumb' );

不知道有哪些 hooks 可用?那麼瞭解一下 WC 內建的 Actions 和 Filters »

修改麪包屑導航的參數

// Code source: https://gist.github.com/dwiash/4064836
function my_WooCommerce_breadcrumbs() {
    return array(
            'delimiter'   => ' / ',
            'wrap_before' => '<nav class="WooCommerce-breadcrumb" itemprop="breadcrumb">',
            'wrap_after'  => '</nav>',
            'before'      => '',
            'after'       => '',
            'home'        => _x( 'Home', 'breadcrumb', 'WooCommerce' ),
        );
}

add_filter( 'WooCommerce_breadcrumb_defaults', 'my_WooCommerce_breadcrumbs' );

參數註釋:

delimiter:分隔符
wrap_before:起始標籤
wrap_after:結束標籤
before:起始標籤之後、麪包屑導航鏈接之前的內容
after:麪包屑導航鏈接之後、結束標籤之前的內容
home:首頁文字,例如像給首頁加 font-awesome,可以這樣設置

'home' => _x( '<i class="icon-home"></i> Home', 'breadcrumb', 'WooCommerce' ),

修改首頁和分類頁面每頁產品數量

每頁顯示多少產品默認跟隨設置 » 閲讀設置 » 博客頁面至多顯示的值,若要產品索引頁和博文索引頁使用不同的設置,可以使用下面的代碼為產品索引頁單獨設置每頁產品數。

add_filter( 'loop_shop_per_page', create_function( '$cols', 'return 24;' ), 20 );

代碼註釋:每頁顯示 24 個產品。

修改分頁導航的參數

// Change args of wc pagination
add_filter( 'WooCommerce_pagination_args', 'theme_wc_pagination_args' );
function theme_wc_pagination_args( $args ){
    $args['prev_text'] = '&laquo; Previous page';
    $args['next_text'] = 'Next page &raquo;';
    $args['end_size'] = 3;
    $args['mid_size'] = 3;
    return $args;
}

參數註釋:

prev_text: 向前翻頁按鈕的文字
next_text: 向後翻頁按鈕的文字
end_size:頁面分頭部、中間、後、尾部三部分顯示,中間用省略號分隔,這個參數控制頭部和尾部顯示多少頁
mid_size: 控制中間顯示多少頁

修改首頁和分類頁每行產品數量

注意,WC 每行產品數量是靠給每行第一個產品元素添加.first class 、每行最後一個添加.last class 實現的,所以這段代碼只能決定在哪裏強制換行,與寬度無關。也就是説如果你設置一行顯示 4 個產品,你不能期待每個 li 的寬度就是 1/4,這個寬度是樣式表設定的,如果樣式表設定的寬度只夠一行放下 3 個,而代碼設定一行顯示 4 個,那就會出現每行個數不等的情況。

/* Change the number of products per column */
add_filter('loop_shop_columns', 'loop_columns');
if (!function_exists('loop_columns')) {
	function loop_columns() {
		return 5;
	}
}

給列表頁每個產品添加產品描述

// Add product description
function theme_wc_single_excerpt(){
    global $post;
    echo '<div class="product-description">' . apply_filters( 'WooCommerce_short_description', $post->post_excerpt ) . '</div>';
}
add_action( 'WooCommerce_after_shop_loop_item_title', 'theme_wc_single_excerpt' );

隱藏相關產品列表

默認產品頁面底部有相關產品一欄,要去掉這個欄目,使用下面的代碼。

function wc_remove_related_products( $args ) {
	return array();
} 
add_filter('WooCommerce_related_products_args','wc_remove_related_products', 10);

修改相關產品列表每行產品數量

用 filter: WooCommerce_output_related_products_args 改變相關產品數量,同樣只是改變換行的位置,需要配合適當的 css 設定寬度才能實現最終效果。

add_filter( 'WooCommerce_output_related_products_args', 'wc_custom_related_products_args' );
function wc_custom_related_products_args( $args ){
    $args = array(
        'posts_per_page' => 2, //共顯示多少產品
        'columns' => 2, //分幾欄顯示
        'orderby' => 'rand'
    );
    return $args;
}

代碼註釋:在每個產品頁面展示最多 10 個相關產品,每行顯示 3 個。

修改產品縮略圖每行數量

和首頁產品每行數量類似,是通過添加.first 和.last class 實現,要真正達到自己想要的效果,還要添加適當的樣式。

add_filter ( 'WooCommerce_product_thumbnails_columns', 'woo_thumb_cols' );
function woo_thumb_cols() {
	return 4; // .last class applied to every 4th thumbnail
}

修改 「Add to Cart」 按鈕的文字

function woo_custom_cart_button_text() { 
	return __('My Button Text', 'WooCommerce'); 
}
add_filter('WooCommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text');

這段代碼在實現 Catalog Mode 中十分有用。

修改貨幣符號

function change_existing_currency_symbol( $currency_symbol, $currency ) {
	switch( $currency ) {
		case 'AUD': $currency_symbol = 'AUD$'; break;
	}
	return $currency_symbol;
}
add_filter('WooCommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);

代碼註釋:將澳元的貨幣符號從默認的 $改為 AUD$。

添加自定義排序選項

下面的代碼演示如何添加一個隨機排序 (Random) 選項,添加其它選項方法類似。

function custom_WooCommerce_get_catalog_ordering_args( $args ) {
	$orderby_value = isset( $_GET['orderby'] ) ? WooCommerce_clean( $_GET['orderby'] ) : apply_filters( 'WooCommerce_default_catalog_orderby', get_option( 'WooCommerce_default_catalog_orderby' ) ); 
	if ( 'random_list' == $orderby_value ) {
		$args['orderby'] = 'rand';
		$args['order'] = '';
		$args['meta_key'] = '';
	}	 
	return $args;
}
add_filter( 'WooCommerce_get_catalog_ordering_args', 'custom_WooCommerce_get_catalog_ordering_args' );
 
function custom_WooCommerce_catalog_orderby( $sortby ) {
	$sortby['random_list'] = __('Sort by random order');
	return $sortby;
}
add_filter( 'WooCommerce_default_catalog_orderby_options', 'custom_WooCommerce_catalog_orderby' );
add_filter( 'WooCommerce_catalog_orderby', 'custom_WooCommerce_catalog_orderby' );

為訂單添加附加費用/手續費

以下代碼演示收取每單商品費用加運費總和的 1% 作為附加費用。

add_action( 'WooCommerce_cart_calculate_fees','WooCommerce_custom_surcharge' );
function WooCommerce_custom_surcharge() {
	global $WooCommerce;
 
	if ( is_admin() && ! defined( 'DOING_AJAX' ) )
		return;
 
	$percentage = 0.01;
	$surcharge = ( $WooCommerce->cart->cart_contents_total + $WooCommerce->cart->shipping_total ) * $percentage;
	$WooCommerce->cart->add_fee( 'Surcharge', $surcharge, false, '' );
	
}

付款成功後立刻發送 invoice

代碼來自:azhowto.com

/**
 * send invoice straight away if payment is successful
 * @param  string $order_id valid payment order id
 * @return null
 */
function send_invoice_upon_payment_successful($order_id) {
  global $WooCommerce;
  $order = new WC_Order($order_id);
  $mailer = $WooCommerce->mailer();
  $mailer->customer_invoice( $order );
}
add_action('WooCommerce_payment_complete', 'send_invoice_upon_payment_successful');

產品列表頁:加入購物車按鈕移動到標題之前

remove_action( 'WooCommerce_after_shop_loop_item', 'WooCommerce_template_loop_add_to_cart', 10 );
add_action( 'WooCommerce_before_shop_loop_item_title', 'WooCommerce_template_loop_add_to_cart', 10 );

產品列表頁:添加鏈接

下面的代碼演示如何在標題之前添加鏈接。

add_action( 'WooCommerce_before_shop_loop_item_title', 'wc_template_loop_additional_links', 10 );
function wc_template_loop_additional_links(){
	?>
	<a href="#" class="button1-link button product_type_simple">Button 1 </a>
	<a href="#" class="button2-link button product_type_simple">Button 2 </a>
	<?php
}

修改產品列表頁按鈕文字

產品列表頁的按鈕文字一般是:add to cart 、 select options, view options 和 read more 。下面代碼演示如何更改這些按鈕文字,使用代碼時,只選擇需要的即可,比如要修改 view options,只需 add_filter( 'grouped_add_to_cart_text', 'wc_add_to_cart_text' ),其它的刪掉。

add_filter( 'WooCommerce_product_add_to_cart_text' , 'custom_WooCommerce_product_add_to_cart_text' );
 
/**
 * custom_WooCommerce_template_loop_add_to_cart
*/
function custom_WooCommerce_product_add_to_cart_text() {
    global $product;
    
    $product_type = $product->product_type;
    
    switch ( $product_type ) {
        case 'external':
            return __( 'Buy product', 'WooCommerce' ); 
        break;
        case 'grouped':
            return __( 'View products', 'WooCommerce' );
        break;
        case 'simple':
            return __( 'Add to cart', 'WooCommerce' );
        break;
        case 'variable':
            return __( 'Select options', 'WooCommerce' );
        break;
        default:
            return __( 'Read more', 'WooCommerce' );
    }
    
}

無論產品是否有屬性,添加到購物車的按鈕名稱都是 Purchase.

官方代碼鏈接

去掉產品頁 reviews 選項卡

add_filter( 'WooCommerce_product_tabs', 'wc_remove_reviews_tab' );
function wc_remove_reviews_tab( $tabs ){    
    unset($tabs['reviews']);
    return $tabs;
}

產品頁添加自定義選項卡

添加一個 features 選項卡,內容可以用 custom field 來寫。

//Add custom tab
add_filter( 'WooCommerce_product_tabs', 'wc_add_features_tab' );
function wc_add_features_tab( $tabs ){    
    global $product;
    $content = get_post_meta( $product->id, 'product_features', true );
    if( !empty($content) ) {
        $tabs[ 'features' ] = array(
            'title'    => 'Features',
            'priority' => 1,
            'callback' => 'wc_features_tabs_panel_content',
            'content'  => $content,  // custom field
        );
    }
    return $tabs;
}
function wc_features_tabs_panel_content( $key, $tab ){
    echo  '<h2>' . $tab['title'] . '</h2>';
    echo $tab['content'];
}

修改 Shop base 頁面的瀏覽器標題

// Change the browser title of shop base page
add_filter('post_type_archive_title', 'theme_wc_shop_browser_title' );
function theme_wc_shop_browser_title( $title ){
	if( $title == __('Products', 'WooCommerce')){
		$shop_page_id = WooCommerce_get_page_id( 'shop' );
		$page_title   = get_the_title( $shop_page_id );
		return $page_title;
	}
	return $title;
}

商店頁面默認的瀏覽器標題 (Browser Title) 是 Products,這個頁面其實是一個 custom post type archive 頁面,雖然內容區域的標題跟隨該頁面的標題,但瀏覽器標題卻是 WordPress 默認的,Products 是一個 custom post type,所以它的 archive 頁面標題就是它的 label 名稱。

上面這段代碼可以讓頁面的標題成為 browser title 。

用户訪問時將產品自動添加到購物車

// add item to cart on visit
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
    if (!is_admin()) {
        global $WooCommerce;
        $product_id = 64;
        $found = false;
        //check if product already in cart
        if (sizeof($WooCommerce->cart->get_cart()) > 0) {
            foreach ($WooCommerce->cart->get_cart() as $cart_item_key => $values) {
                $_product = $values['data'];
                if ($_product->id == $product_id)
                    $found = true;
            }
        // if product not found, add it
            if (!$found)
                $WooCommerce->cart->add_to_cart($product_id);
        } else {
        // if no products in cart, add it
            $WooCommerce->cart->add_to_cart($product_id);
        }
    }
}

虛擬產品:付款成功後訂單狀態立即變為 complete

代碼來自:http://www.skyverge.com/product/WooCommerce-order-status-control/

add_filter( 'WooCommerce_payment_complete_order_status', 'virtual_order_payment_complete_order_status', 10, 2 );
 
function virtual_order_payment_complete_order_status( $order_status, $order_id ) {
  $order = new WC_Order( $order_id );
 
  if ( 'processing' == $order_status &&
       ( 'on-hold' == $order->status || 'pending' == $order->status || 'failed' == $order->status ) ) {
 
    $virtual_order = null;
 
    if ( count( $order->get_items() ) > 0 ) {
 
      foreach( $order->get_items() as $item ) {
 
        if ( 'line_item' == $item['type'] ) {
 
          $_product = $order->get_product_from_item( $item );
 
          if ( ! $_product->is_virtual() ) {
            // once we've found one non-virtual product we know we're done, break out of the loop
            $virtual_order = false;
            break;
          } else {
            $virtual_order = true;
          }
        }
      }
    }
 
    // virtual order, mark as completed
    if ( $virtual_order ) {
      return 'completed';
    }
  }
 
  // non-virtual order, return original status
  return $order_status;
}