WordPress教程

WooCommerce 实用代码汇总自定义WooCommerce功能

阿里云

用过了一段 WooCommerce 时间后,发现 WooCommerce 在打造 WordPress 商城这一块功能相当强大,也很成熟了。但是在刚刚接触 WooCommerce 时却遇到了不少的麻烦,一是中文相关的 WooCommerce 参考资料真的是太少了,不知道与国内的用户少有关系。

另一方面发现 WooCommerce 对于国人来说还存在很大的“改进”空间。例如添加到购物车,只有简单的链接,没有像淘宝那样的购物车侧边栏。最大的问题就是 WooCommerce 的账户管理中心功能简陋,想要的东西没有(当然,插件提供了接口可以自已添加)。

也想出现在这里?联系我们
创客主机

最先想到解决 WooCommerce 这些问题,是通过 WooCommerce 插件来搞定 。搜索了一下 WooCommerce 的相关插件,确实非常多,几乎想要的功能都可以找到对应的 WooCommerce 插件。但是本着少用插件的原则,最后还是找到一些 WooCommerce 实用代码,作用与插件是一样的。

大家在使用这些 WooCommerce 代码记得先学习一下 WooCommerce 的官方文档,实际上相当多的代码 WooCommerce 官方已经给出了示例,我们只需要在主题的函数文件中调用即可。另外,WooCommerce 的版本也在不断地更新当中,有些代码可能在某些版本的 WooCommerce 没有效果,请注意看自己用的版本和代码对应的版本有没有出入。

本篇文章就来分享一下 WooCommerce 实用代码,涉及到购物车、订单页面、店铺首页、商品详情页面、结算页面等,通过这些代码我们可以有针对性地进行相应的调整。

section

第一次接触 WooCommerce 商城的朋友,请参考:WordPress 商城搭建-WooCommerce 安装和 Paypal,支付宝,微信设置。注意:代码如果没有特别说明,就放在 functions.php 文件的”?>”前面。

购物车中排除已设置为隐藏的产品

WooCommerce 有些设置为隐藏的商品,如果用户购买了后会显示在购物车中,利用以下代码就可以将设置为隐藏的产品在购物车中不可见。

  1. /**
  2.  * @snippet       Exclude Hidden Products from Cart Count - WooCommerce
  3.  * @author        Rodolfo Melogli
  4.  * @compatible    WooCommerce 3.4.5
  5.  */
  6.  
  7. // PLEASE NOTE: EMPTY THE CART BEFORE TESTING
  8.  
  9. add_filter( 'woocommerce_cart_contents_count', 'bbloomer_exclude_hidden_minicart_counter' );
  10.  
  11. function bbloomer_exclude_hidden_minicart_counter( $quantity ) {
  12.   $hidden = 0;
  13.   foreach( WC()->cart->get_cart() as $cart_item ) {
  14. 	 $product = $cart_item['data'];
  15. 	 if ( $product->get_catalog_visibility() == 'hidden' ) $hidden += $cart_item['quantity'];
  16.   }
  17.   $quantity -= $hidden;
  18.   return $quantity;
  19. }

若商品在购物车中已存在,则重名“添加到购物车”按钮

如果想要 WooCommerce 在用户点击添加到购物车后,提示该商品已经在购物车中了,你可以用以下方法。

  1. /**
  2. * @snippet       Change "Add to Cart" Button Label if Product Already @ Cart
  3. * @testedwith    Woo 3.3.4
  4. */
  5.  
  6. // Part 1
  7.  
  8. // Edit Single Product Page Add to Cart
  9.  
  10. add_filter( 'woocommerce_product_single_add_to_cart_text', 'bbloomer_custom_add_cart_button_single_product' );
  11. function bbloomer_custom_add_cart_button_single_product( $label ) {
  12. foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
  13. $product = $values['data'];
  14. if( get_the_ID() == $product->get_id() ) {
  15. $label = __('已添加到购物车,还要一个?', 'woocommerce');
  16. }
  17. }
  18.  
  19. return $label;
  20.  
  21. }
  22.  
  23. // Part 2
  24. // Edit Loop Pages Add to Cart
  25. add_filter( 'woocommerce_product_add_to_cart_text', 'bbloomer_custom_add_cart_button_loop', 99, 2 );
  26. function bbloomer_custom_add_cart_button_loop( $label, $product ) {
  27. if ( $product->get_type() == 'simple' && $product->is_purchasable() && $product->is_in_stock() ) {
  28. foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
  29. $_product = $values['data'];
  30. if( get_the_ID() == $_product->get_id() ) {
  31. $label = __('已添加到购物车,还要一个?', 'woocommerce');
  32. }
  33. }
  34.  
  35. }
  36. return $label;
  37. }

调整货币符号

将澳元的货币符号从默认的$改为 AUD$。

  1. function change_existing_currency_symbol( $currency_symbol, $currency ) {
  2.     switch( $currency ) {
  3.         case 'AUD': $currency_symbol = 'AUD$'; break;
  4.     }
  5.     return $currency_symbol;
  6. }
  7. add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);

section

在店铺页面按照库存排序显示产品

WooCommerce 默认的的店铺首页会有按钮热度、关注度、价格等来排序,我们可以自己添加一个自定义排序,设置按照产品库存排序。

1: Sort Products by Stock Status @ WooCommerce Shop

  1. /**
  2. * @snippet       Sort Products By Stock Status - WooCommerce Shop
  3. */
  4.  
  5. add_action( 'woocommerce_product_query', 'bbloomer_sort_by_stock_status_then_alpha', 999 );
  6. function bbloomer_sort_by_stock_status_then_alpha( $query ) {
  7. if ( is_admin() ) return;
  8. $query->set( 'meta_key', '_stock_status' );
  9. $query->set( 'orderby', array( 'meta_value' => 'ASC' ) );
  10. }

2: Sort Products SHORTCODE by Stock Status

  1. /**
  2. * @snippet       Sort Products Shortcode By Stock Status
  3. * @author        Rodolfo Melogli
  4. * @compatible    WooCommerce 3.4.5
  5. */
  6.  
  7. // Note: products shortcode docs https://docs.woocommerce.com/document/woocommerce-shortcodes/#section-6
  8. // In order for the snippet to work, you must add the parameter orderby = "stock" to the shortcode
  9. // You can add more parameters to it of course e.g. limit, paginate, etc. It's all in the docs
  10. add_filter('woocommerce_shortcode_products_query', 'bbloomer_sort_by_stock_status_shortcode', 999, 3);
  11. function bbloomer_sort_by_stock_status_shortcode( $args, $atts, $type ) {
  12. if ( $atts['orderby'] == "stock" ) {
  13. $args['orderby']  = array( 'meta_value' => 'ASC' );
  14. $args['meta_key'] = '_stock_status';
  15. }
  16. return $args;
  17. }

店铺首页中显示商品品牌

WooCommerce 默认的不会显示某一个产品的品牌,当然我们可以用以下方法搞定:

  1. add_action( 'woocommerce_after_shop_loop_item_title', 'bbloomer_show_woocommerce_brands_loop', 8 );
  2.  
  3. function bbloomer_show_woocommerce_brands_loop() {
  4.     global $post;
  5.     echo get_brands( $post->ID );
  6. }

店铺显示某用户已经购买过某商品

  1. add_action( 'woocommerce_after_shop_loop_item', 'user_logged_in_product_already_bought', 30 );
  2.  
  3. function user_logged_in_product_already_bought() {
  4. if ( is_user_logged_in() ) {
  5. global $product;
  6. $current_user = wp_get_current_user();
  7. if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->get_id() ) ) echo '
  8. ♥ Hey ' . $current_user->first_name . ', you\'ve purchased this in the past. Buy again?
  9. ';
  10. }
  11. }

禁用或者修改面包屑导航位置

删除禁用默认的面包屑导航

  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' );

修改面包屑导航的参数:

  1. // Code source: https://gist.github.com/dwiash/4064836
  2. function my_woocommerce_breadcrumbs() {
  3.     return array(
  4.             'delimiter'   => ' / ',
  5.             'wrap_before' => '
  6. ',
  7.             'wrap_after'  => '
  8. ',
  9.             'before'      => '',
  10.             'after'       => '',
  11.             'home'        => _x( 'Home', 'breadcrumb', 'woocommerce' ),
  12.         );
  13. }
  14.  
  15. add_filter( 'woocommerce_breadcrumb_defaults', 'my_woocommerce_breadcrumbs' );

参数注释:

delimiter:分隔符
wrap_before:起始标签
wrap_after:结束标签
before:起始标签之后、面包屑导航链接之前的内容
after:面包屑导航链接之后、结束标签之前的内容
home:首页文字,例如像给首页加 font-awesome,可以这样设置

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

section

产品没有描述时设置一个默认的描述

WooCommerce 的商品页面如何没有描述会显示空白,这显然不怎么好看,我们可以设置一个段描述用于在没有描述的情况作为默认显示内容。

  1. /**
  2.  * @snippet       Show Custom Content When Short Description Empty - WooCommerce
  3.  * @author        Rodolfo Melogli
  4.  * @compatible    WooCommerce 3.4.5
  5.  */
  6.  
  7. add_filter( 'woocommerce_short_description', 'bbloomer_echo_short_desc_if_no_short_desc' );
  8.  
  9. function bbloomer_echo_short_desc_if_no_short_desc( $post_excerpt ) {
  10. 	if ( empty ( $post_excerpt ) ) {
  11. 		$post_excerpt = '<p class="default-short-desc">';
  12. 		$post_excerpt .= 'This is the default, global, short description.<br>It will show if <b>no short description has been entered!</b>';
  13. 		$post_excerpt .= '</p>';
  14. 	}
  15. 	return $post_excerpt;
  16. }

隐藏相关产品推荐

WooCommerce 默认的会在商品的页面下方显示 4 个相关的产品,如果你不想要,可以用以下代码去掉它。

  1. remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );

添加“继续购物”按钮

当用户在 WooCommerce 的产品页面点击添加到购物车后,如果你希望增加一个显示“继续购物”的按钮,可以使用以下代码:

  1.     add_action( ‘woocommerce_single_product_summary’, ‘bbloomer_continue_shopping_button’, 31 );
  2.  
  3.     function bbloomer_continue_shopping_button() {
  4.       if ( wp_get_referer() ) echo<a class=”button continue” href=”‘ . wp_get_referer() . ‘”>继续购物</a>;
  5.     }

使用视频作为产品展示而不是静态的图片

WooCommerce 默认的是用图片作为产品展示,我们也可以使用以下代码来让产品变成视频展示。

  1.     add_action( ‘woocommerce_before_single_product’, ‘bbloomer_show_video_not_image’ );
  2.  
  3.     function bbloomer_show_video_not_image() {
  4.  
  5.     // Do this for product ID = 282 only
  6.  
  7.     if ( is_single( '282' ) ) {
  8.  
  9.     remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
  10.  
  11.     remove_action( 'woocommerce_product_thumbnails', 'woocommerce_show_product_thumbnails', 20 );
  12.  
  13.     add_action( 'woocommerce_before_single_product_summary', 'bbloomer_show_product_video', 30 );
  14.  
  15.     }
  16.  
  17.     }
  18.  
  19.     function bbloomer_show_product_video() {
  20.  
  21.     echo '<div class="woocommerce-product-gallery">';
  22.  
  23.     // get video embed HTML from YouTube
  24.  
  25.     echo '<iframe width="560" height="315" src="https://22vd.com/embed/JHN7viKRxbQ?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>';
  26.  
  27.     echo</div>;
  28.  
  29.     }

调整相关产品的数量

WooCommerce 默认的相关产品数量是 4 个,你可以自定义显示数量。

  1. add_filter( 'woocommerce_output_related_products_args', 'bbloomer_change_number_related_products', 9999 );
  2. function bbloomer_change_number_related_products( $args ) {
  3.  $args['posts_per_page'] = 4; // # of related products
  4.  $args['columns'] = 4; // # of columns per row
  5.  return $args;
  6. }

section

WooCommerce 订单管理中添加自定义栏

以下代码可以在 WooCommerce 的订单管理页面添加到以国家为参数的列。

  1. /**
  2.  * @snippet       Add Column to Orders Table (e.g. Billing Country) - WooCommerce
  3.  * @author        Rodolfo Melogli
  4.  * @compatible    WooCommerce 3.4.5
  5.  */
  6.  
  7. add_filter( 'manage_edit-shop_order_columns', 'bbloomer_add_new_order_admin_list_column' );
  8. function bbloomer_add_new_order_admin_list_column( $columns ) {
  9.     $columns['billing_country'] = 'Country';
  10.     return $columns;
  11. }
  12. add_action( 'manage_shop_order_posts_custom_column', 'bbloomer_add_new_order_admin_list_column_content' );
  13. function bbloomer_add_new_order_admin_list_column_content( $column ) {
  14.     global $post;
  15.     if ( 'billing_country' === $column ) {
  16.         $order = wc_get_order( $post->ID );
  17.         echo $order->get_billing_country();	 
  18.     }
  19. }

去掉结算页面的“什么是 Paypal”“What is PayPal?”

WooCommerce 在使用 Paypal 付款时会显示一个“什么是 Paypal”“What is PayPal?”的提示,如果你觉得不好看的话可以用以下方法来删除它:

  1.     add_filter( 'woocommerce_gateway_icon', 'bbloomer_remove_what_is_paypal', 10, 2 );
  2.  
  3.     function bbloomer_remove_what_is_paypal( $icon_html, $gateway_id ) {
  4.  
  5.     // the apply_filters comes with 2 parameters: $icon_html, $this->id
  6.  
  7.     // hence we declare 2 parameters within the function
  8.  
  9.     // and the hook above takes the "2" as we decided to pass 2 variables
  10.  
  11.     if( 'paypal' == $gateway_id ) {
  12.  
  13.     // we use one of the passed variables to make sure we only
  14.  
  15.     // run this function for the gateway ID == 'paypal'
  16.  
  17.     $icon_html = '<img src="wzfou.com/wp-content/plugins/woocommerce/includes/gateways/paypal/assets/images/paypal.png" alt="PayPal Acceptance Mark">';
  18.  
  19.     // in here we define our own $icon_html
  20.  
  21.     // note there is no mention of the "What is PayPal"
  22.  
  23.     // all we want is to repeat the part with the paypal logo
  24.  
  25.     }
  26.  
  27.     // endif
  28.  
  29.     return $icon_html;
  30.  
  31.     // we send the $icon_html variable back to the system
  32.  
  33.     // if PayPal, the system will use our custom $icon_html
  34.  
  35.     // if not, the system will use the original $icon_html
  36.  
  37.     }

section

显示用户已经购买过的产品

如果你想让用户首先在 WooCommerce 的个人订单管理页面看到自己曾经购买过的产品列表,可以先在 function.php 文件中添加以下代码:

  1. /**
  2.  * @snippet       Display All Products Purchased by User via Shortcode - WooCommerce
  3.  * @author        Rodolfo Melogli
  4.  * @compatible    Woo 3.4.5
  5.  */
  6.  
  7. // Note: this will only return purchased products for completed and processing orders
  8.  
  9. add_shortcode( 'my_products', 'bbloomer_user_products_bought' );
  10.  
  11. function bbloomer_user_products_bought() {
  12. global $product, $woocommerce, $woocommerce_loop;
  13. $columns = 3;
  14. $current_user = wp_get_current_user();
  15. $args = array(
  16.     'post_type' => 'product',
  17.     'post_status' => 'publish',
  18.     'posts_per_page' => -1
  19. );
  20. $loop = new WP_Query($args);
  21.  
  22. ob_start();
  23.  
  24. woocommerce_product_loop_start();
  25.  
  26. while ( $loop->have_posts() ) : $loop->the_post();
  27. $theid = get_the_ID();
  28. if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $theid ) ) {
  29. wc_get_template_part( 'content', 'product' );
  30. }
  31. endwhile;
  32.  
  33. woocommerce_product_loop_end();
  34.  
  35. woocommerce_reset_loop();
  36. wp_reset_postdata();
  37.  
  38. return '
  39. ' . ob_get_clean() . '
  40. ';
  41. }

然后在你需要显示用户所购买过的所有产品的页面添加以下短代码即可:

  1. [my_products]

添加新的菜单到账户中心

默认的话,在 WooCommerce 的账户中心只显示资料、订单、地址、退出等菜单,我们可以用以下方法来添加新的菜单。

  1.     //添加my-account自定义导航及页面
  2.     /**
  3.     * @snippet       WooCommerce Add New Tab @ My Account
  4.     * @credits       https://github.com/woothemes/woocommerce/wiki/2.6-Tabbed-My-Account-page
  5.     * @author        Rodolfo Melogli
  6.     * @testedwith    WooCommerce 3.4.5
  7.     */
  8.  
  9.  
  10.     // ——————
  11.     // 1. Register new endpoint to use for My Account page
  12.     // Note: Resave Permalinks or it will give 404 error
  13.  
  14.     function bbloomer_add_premium_support_endpoint() {
  15.         add_rewrite_endpoint( 'premium-support', EP_ROOT | EP_PAGES );
  16.     }
  17.  
  18.     add_action( 'init', 'bbloomer_add_premium_support_endpoint' );
  19.  
  20.  
  21.     // ——————
  22.     // 2. Add new query var
  23.  
  24.     function bbloomer_premium_support_query_vars( $vars ) {
  25.         $vars[] = 'premium-support';
  26.         return $vars;
  27.     }
  28.  
  29.     add_filter( 'query_vars', 'bbloomer_premium_support_query_vars', 0 );
  30.  
  31.  
  32.     // ——————
  33.     // 3. Insert the new endpoint into the My Account menu
  34.  
  35.     function bbloomer_add_premium_support_link_my_account( $items ) {
  36.         $items['premium-support'] = '联系我们';
  37.         return $items;
  38.     }
  39.  
  40.     add_filter( 'woocommerce_account_menu_items', 'bbloomer_add_premium_support_link_my_account' );
  41.  
  42.  
  43.     // ——————
  44.     // 4. Add content to the new endpoint
  45.  
  46.     function bbloomer_premium_support_content() {
  47.     echo '<h3>联系我们</h3><p>有任何问题,欢迎与站长Qi取得联系。Qi的QQ号:xxxxxx,微信号:xxxxx。添加好友请注明“店铺订单”字样。更多的联系方式在:<a href="//22vd.com/contact/" target=""_blank" rel="noopener">联系站长</a>。</p>';
  48.     // echo do_shortcode( ' /* your shortcode here */ ' );
  49.     }
  50.  
  51.     add_action( 'woocommerce_account_premium-support_endpoint', 'bbloomer_premium_support_content' );
  52.     // Note: add_action must follow 'woocommerce_account_{your-endpoint-slug}_endpoint' format

section

WooCommerce 虽然说是国外人开发的插件,但是却提供非常多的 Hook,我们可以通过主题的函数文件自定义 WooCommerce 各种设置,上面的代码只是 wzfou.com 在使用过程觉得可以用得上的,实际上官方还提供非常多的自定义函数。

当然,也有朋友会觉得修改代码有些困难,WooCommerce 其实已经有类似的插件了,例如 WooCommerce 菜单插件,可以方便你自由地添加自定义链接到“我的账户”中,另外相关 WooCommerce 优化插件,基本上是整合了以下的代码。

WooCommerce 实用代码汇总自定义 WooCommerce 功能

已有 443 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!