本文整理了一些适用于 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;
}