本文整理了一些WooCommerce代码合集,方便查阅和使用,更是为了理清思路,提高自己。以下WooCommerce简称WC,代码放在主题的functions.php中即可。

修改首页和分类页面每页产品数量

每页显示多少产品默认跟随设置 » 阅读设置 » 博客页面至多显示的值,若要产品索引页和博文索引页使用不同的设置,可以使用下面的代码为产品索引页单独设置每页产品数。

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

  代码注释:每页显示24个产品。代码放在主题的functions.php中即可

下面整理更多适用于WooCommerce的短代码,方便查阅和使用,更是为了理清思路,提高自己。以下WooCommerce简称WC,代码放在主题的functions.php中即可。

WooCommrce官方代码集»

在主题中声明对WooCommerce的支持

1
2
3
4
add_action( 'after_setup_theme', 'woocommerce_support' );
function woocommerce_support() {
    add_theme_support( 'woocommerce' );
}

  

禁用WooCommerce默认样式

1
2
// Disable WooCommerce styles
define('WOOCOMMERCE_USE_CSS', false);

禁用默认样式,就要引入自己的样式,可以直接写在style.css中,也可以另外写一个样式表

1
2
3
4
5
6
7
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面包屑导航

修改面包屑导航位置

首先删除默认的面包屑导航

1
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0);

将导航添加到其它位置,例如放在header.php中,则直接在header.php适当位置插入如下代码

1
if( function_exists( 'woocommerce_breadcrumb') ) woocommerce_breadcrumb();

也可以用add_action添加,例如

1
add_action( 'woocommerce_after_main_content', 'woocommerce_breadcrumb' );

不知道有哪些hooks可用?那么了解一下WC内建的Actions和Filters

修改面包屑导航的参数

1
2
3
4
5
6
7
8
9
10
11
// Code source: https://gist.github.com/dwiash/4064836function my_woocommerce_breadcrumbs() {
    return array(
        'delimiter'   => ' / ',
        'wrap_before' => '<nav 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,可以这样设置

1
'home' => _x( '<i></i> Home', 'breadcrumb', 'woocommerce' ),

  

修改分页导航的参数

1
2
3
4
5
6
7
8
9
// Change args of wc pagination
add_filter( 'woocommerce_pagination_args', 'theme_wc_pagination_args' );
function theme_wc_pagination_args( $args ){
    $args['prev_text'] = '« Previous page';
    $args['next_text'] = 'Next page »';
    $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个,那就会出现每行个数不等的情况。

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

  

给列表页每个产品添加产品描述

1
2
3
4
5
6
// Add product description
function theme_wc_single_excerpt(){
    global $post;
    echo '<div>' . apply_filters( 'woocommerce_short_description', $post->post_excerpt ) . '</div>';
}
add_action( 'woocommerce_after_shop_loop_item_title', 'theme_wc_single_excerpt' );

  

隐藏相关产品列表

默认产品页面底部有相关产品一栏,要去掉这个栏目,使用下面的代码。

1
2
3
4
function wc_remove_related_products( $args ) {
    return array();
}
add_filter('woocommerce_related_products_args','wc_remove_related_products', 10);

  

修改相关产品列表每行产品数量

用重新定义woocommerce_output_related_products函数的方法改变相关产品数量,同样只是改变换行的位置,需要配合适当的css设定宽度才能实现最终效果。

1
2
3
4
/* Change number of relapted products */
function woocommerce_output_related_products() {
    woocommerce_related_products(10,3); // Display 10 products in rows of 3
}

  代码注释:在每个产品页面展示最多10个相关产品,每行显示3个。

修改产品缩略图每行数量

和首页产品每行数量类似,是通过添加.first和.last class实现,要真正达到自己想要的效果,还要添加适当的样式。

1
2
3
4
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”按钮的文字

1
2
3
4
function woo_custom_cart_button_text() {
    return __('My Button Text', 'woocommerce');
}
add_filter('single_add_to_cart_text', 'woo_custom_cart_button_text');

  这段代码在实现Catalog Mode中十分有用。

修改货币符号

1
2
3
4
5
6
7
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)选项,添加其它选项方法类似。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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%作为附加费用。

1
2
3
4
5
6
7
8
9
10
add_action( 'woocommerce_calculate_totals','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, '' );
    $woocommerce->cart->fee_total += $surcharge;
}

  

付款成功后立刻发送Invoice

代码来自:azhowto.com

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * 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');

  

产品列表页:加入购物车按钮移动到标题之前

1
2
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 );

  

产品列表页:添加链接

下面的代码演示如何在标题之前添加链接。

1
2
3
4
5
6
7
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’ ),其它的删掉。

1
2
3
4
5
6
7
8
9
add_filter( 'variable_add_to_cart_text', 'wc_add_to_cart_text' ); //默认为select options
add_filter( 'grouped_add_to_cart_text', 'wc_add_to_cart_text' ); //默认为view options
add_filter( 'add_to_cart_text', 'wc_add_to_cart_text' ); //默认为add to cart
add_filter( 'external_add_to_cart_text', 'wc_add_to_cart_text' ); //默认为read more
add_filter( 'not_purchasable_text', 'wc_add_to_cart_text' );//默认为read more
add_filter( 'out_of_stock_add_to_cart_text', 'wc_add_to_cart_text' );//默认为read more
function wc_add_to_cart_text(){
    return 'Purchase';
}

  无论产品是否有属性,添加到购物车的按钮名称都是Purchase.

去掉产品页Reviews选项卡

1
2
3
4
5
add_filter( 'woocommerce_product_tabs', 'wc_remove_reviews_tab' );
function wc_remove_reviews_tab( $tabs ){
    unset($tabs['reviews']);
    return $tabs;
}

  

产品页添加自定义选项卡

添加一个features选项卡,内容可以用custom field来写。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//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页面的浏览器标题

1
2
3
4
5
6
7
8
9
10
// 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。

用户访问时将产品自动添加到购物车

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 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/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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;
}

  http://www.solagirl.net/woocommerce-code-sinppets.html

WooCommerce代码合集整理的更多相关文章

  1. 计算机视觉与模式识别代码合集第二版two

    Topic Name Reference code Image Segmentation Segmentation by Minimum Code Length AY Yang, J. Wright, ...

  2. 计算机视觉与模式识别代码合集第二版three

    计算机视觉与模式识别代码合集第二版three     Topic Name Reference code Optical Flow Horn and Schunck's Optical Flow   ...

  3. [ZZ] UIUC同学Jia-Bin Huang收集的计算机视觉代码合集

    UIUC同学Jia-Bin Huang收集的计算机视觉代码合集 http://blog.sina.com.cn/s/blog_4a1853330100zwgm.htmlv UIUC的Jia-Bin H ...

  4. 【转载】GitHub 标星 1.2w+,超全 Python 常用代码合集,值得收藏!

    本文转自逆袭的二胖,作者二胖 今天给大家介绍一个由一个国外小哥用好几年时间维护的 Python 代码合集.简单来说就是,这个程序员小哥在几年前开始保存自己写过的 Python 代码,同时把一些自己比较 ...

  5. git常用代码合集

    git常用代码合集 1. Git init:初始化一个仓库 2. Git add 文件名称:添加文件到Git暂存区 3. Git commit -m “message”:将Git暂存区的代码提交到Gi ...

  6. 常用的js代码合集

    !function(util){ window.Utils = util(); }( function(){ //document_event_attributes var DEA = "d ...

  7. paper 15 :整理的CV代码合集

    这篇blog,原来是西弗吉利亚大学的Li xin整理的,CV代码相当的全,不知道要经过多长时间的积累才会有这么丰富的资源,在此谢谢LI Xin .我现在分享给大家,希望可以共同进步!还有,我需要说一下 ...

  8. UIUC同学Jia-Bin Huang收集的计算机视觉代码合集

    转自:http://blog.sina.com.cn/s/blog_631a4cc40100wrvz.html   UIUC的Jia-Bin Huang同学收集了很多计算机视觉方面的代码,链接如下: ...

  9. 转--Android学习笔记-实用代码合集

    http://blog.csdn.net/yf210yf/article/details/7295577 转载请注明原文出处:奔跑的蜗牛(袁方的技术博客)点击打开链接 一.当利用textview显示内 ...

随机推荐

  1. 第09组 Beta冲刺(1/5)

    队名:观光队 链接 组长博客 作业博客 组员实践情况 王耀鑫 过去两天完成了哪些任务 文字/口头描述 任务分配 展示GitHub当日代码/文档签入记录 接下来的计划 完成短租车,页面美化 还剩下哪些任 ...

  2. 团队作业第五次—项目冲刺-Day4

    Day4 part1-SCRUM: 项目相关 作业相关 具体描述 所属班级 2019秋福大软件工程实践Z班 作业要求 团队作业第五次-项目冲刺 作业正文 hunter--冲刺集合 团队名称 hunte ...

  3. NOI 2010 海拔(最小割转最短路)

    题意 https://www.lydsy.com/JudgeOnline/problem.php?id=2007 思路 首先可以发现一个结论,每个位置的海拔只有能是 \(0\) 和 \(1\) ,然后 ...

  4. navicat 11.2.7破解

    1,软件安装包目录 2,根据电脑系统安装x64或者x86,安装完成之后将PatchNavicat.exe放到navicat的安装目录下 3,右键以管理员身份运行PatchNavicat.exe,或者双 ...

  5. vue 学习记录

    模板:通常是指html模板 组件component的概念: 在 Vue 里,一个组件本质上是一个拥有预定义选项的一个 Vue 实例, 将组件看作自定义的HTML元素.使用组件的前提是创建并注册组件 v ...

  6. Jenkins Pipeline 参数详解

    Pipeline 是什么 Jenkins Pipeline 实际上是基于 Groovy 实现的 CI/CD 领域特定语言(DSL),主要分为两类,一类叫做 Declarative Pipeline,一 ...

  7. 用欧拉计划学Rust语言(第17~21题)

    最近想学习Libra数字货币的MOVE语言,发现它是用Rust编写的,所以先补一下Rust的基础知识.学习了一段时间,发现Rust的学习曲线非常陡峭,不过仍有快速入门的办法. 学习任何一项技能最怕没有 ...

  8. asp.net core 2.1 容器中使用 System.Drawing.Common 的问题

  9. .NET Standard和.NET Core是什么关系(转载)

    .NET Standard vs .NET Core 问: I have read about the difference between .NET Standard and .NET Core, ...

  10. FileChannel(API详解)

    1.两种获取通道的方法FileChannel.open()的方式 FileChannel channell = FileChannel.open(Paths.get("a.txt" ...