建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

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

GG网络技术分享 2025-03-18 16:05 0


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

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

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

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

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

第一次接触 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. // PLEASE NOTE: EMPTY THE CART BEFORE TESTING
  7. add_filter( 'woocommerce_cart_contents_count', 'bbloomer_exclude_hidden_minicart_counter' );
  8. function bbloomer_exclude_hidden_minicart_counter( $quantity ) {
  9.   $hidden = 0;
  10.   foreach( WC()->cart->get_cart() as $cart_item ) {
  11.  $product = $cart_item['data'];
  12.  if ( $product->get_catalog_visibility() == 'hidden' ) $hidden += $cart_item['quantity'];
  13.   }
  14.   $quantity -= $hidden;
  15.   return $quantity;
  16. }

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

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

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

调整货币符号

将澳元的货币符号从默认的$改为 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);

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

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

1: Sort Products by Stock Status @ WooCommerce Shop

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

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. // Note: products shortcode docs https://docs.woocommerce.com/document/woocommerce-shortcodes/#section-6
  7. // In order for the snippet to work, you must add the parameter orderby = "stock" to the shortcode
  8. // You can add more parameters to it of course e.g. limit, paginate, etc. It's all in the docs
  9. add_filter('woocommerce_shortcode_products_query', 'bbloomer_sort_by_stock_status_shortcode', 999, 3);
  10. function bbloomer_sort_by_stock_status_shortcode( $args, $atts, $type ) {
  11. if ( $atts['orderby'] == "stock" ) {
  12. $args['orderby']  = array( 'meta_value' => 'ASC' );
  13. $args['meta_key'] = '_stock_status';
  14. }
  15. return $args;
  16. }

店铺首页中显示商品品牌

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

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

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

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

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

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

  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. add_filter( 'woocommerce_breadcrumb_defaults', 'my_woocommerce_breadcrumbs' );

参数注释:

delimiter:分隔符

wrap_before:起始标签

wrap_after:结束标签

before:起始标签之后、面包屑导航链接之前的内容

after:面包屑导航链接之后、结束标签之前的内容

home:首页文字,例如像给首页加 font-awesome,可以这样设置

  1. 'home' => _x( ' Home', 'breadcrumb', 'woocommerce' ),

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

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

  1. /**
  2.  * @snippet       Show Custom Content When Short Description Empty - WooCommerce
  3.  * @author        Rodolfo Melogli
  4.  * @compatible    WooCommerce 3.4.5
  5.  */
  6. add_filter( 'woocommerce_short_description', 'bbloomer_echo_short_desc_if_no_short_desc' );
  7. function bbloomer_echo_short_desc_if_no_short_desc( $post_excerpt ) {
  8. if ( empty ( $post_excerpt ) ) {
  9. $post_excerpt = '

    '

     

    ;
  10. $post_excerpt .= 'This is the default, global, short description.

    It will show if no short description has been entered!'
    ;
  11. $post_excerpt .= '';
  12. }
  13. return $post_excerpt;
  14. }

隐藏相关产品推荐

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.     function bbloomer_continue_shopping_button() {
  3.       if ( wp_get_referer() ) echoa class=”button continue” href=”‘ . wp_get_referer() . ‘”>继续购物a>;
  4.     }

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

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

  1.     add_action( ‘woocommerce_before_single_product’, ‘bbloomer_show_video_not_image’ );
  2.     function bbloomer_show_video_not_image() {
  3.     // Do this for product ID = 282 only
  4.     if ( is_single( '282' ) ) {
  5.     remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
  6.     remove_action( 'woocommerce_product_thumbnails', 'woocommerce_show_product_thumbnails', 20 );
  7.     add_action( 'woocommerce_before_single_product_summary', 'bbloomer_show_product_video', 30 );
  8.     }
  9.     }
  10.     function bbloomer_show_product_video() {
  11. echo '
  12.     // get video embed  from YouTube
  13. echo '';
  14.     echo ‘div>;
  15.     }
  16.  

调整相关产品的数量

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. }

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. add_filter( 'manage_edit-shop_order_columns', 'bbloomer_add_new_order_admin_list_column' );
  7. function bbloomer_add_new_order_admin_list_column( $columns ) {
  8.     $columns['billing_country'] = 'Country';
  9.     return $columns;
  10. }
  11. add_action( 'manage_shop_order_posts_custom_column', 'bbloomer_add_new_order_admin_list_column_content' );
  12. function bbloomer_add_new_order_admin_list_column_content( $column ) {
  13.     global $post;
  14.     if ( 'billing_country' === $column ) {
  15.         $order = wc_get_order( $post->ID );
  16.         echo $order->get_billing_country();
  17.     }
  18. }

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

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

  1.     add_filter( 'woocommerce_gateway_icon', 'bbloomer_remove_what_is_paypal', 10, 2 );
  2.     function bbloomer_remove_what_is_paypal( $icon_html, $gateway_id ) {
  3.     // the apply_filters comes with 2 parameters: $icon_html, $this->id
  4.     // hence we declare 2 parameters within the function
  5.     // and the hook above takes the "2" as we decided to pass 2 variables
  6.     if( 'paypal' == $gateway_id ) {
  7.     // we use one of the passed variables to make sure we only
  8.     // run this function for the gateway ID == 'paypal'
  9.     $icon_html = 'PayPal Acceptance Mark';
  10.     // in here we define our own $icon_html
  11.     // note there is no mention of the "What is PayPal"
  12.     // all we want is to repeat the part with the paypal logo
  13.     }
  14.     // endif
  15.     return $icon_html;
  16.     // we send the $icon_html variable back to the system
  17.     // if PayPal, the system will use our custom $icon_html
  18.     // if not, the system will use the original $icon_html
  19.     }

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

如果你想让用户首先在 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. // Note: this will only return purchased products for completed and processing orders
  7. add_shortcode( 'my_products', 'bbloomer_user_products_bought' );
  8. function bbloomer_user_products_bought() {
  9. global $product, $woocommerce, $woocommerce_loop;
  10. $columns = 3;
  11. $current_user = wp_get_current_user();
  12. $args = array(
  13.     'post_type' => 'product',
  14.     'post_status' => 'publish',
  15.     'posts_per_page' => -1
  16. );
  17. $loop = new WP_Query($args);
  18. ob_start();
  19. woocommerce_product_loop_start();
  20. while ( $loop->have_posts() ) : $loop->the_post();
  21. $theid = get_the_ID();
  22. if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $theid ) ) {
  23. wc_get_template_part( 'content', 'product' );
  24. }
  25. endwhile;
  26. woocommerce_product_loop_end();
  27. woocommerce_reset_loop();
  28. wp_reset_postdata();
  29. return '
  30. ' . ob_get_clean() . '
  31. ';
  32. }

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

  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.     // 1. Register new endpoint to use for My Account page
  10.     // Note: Resave Permalinks or it will give 404 error
  11.     function bbloomer_add_premium_support_endpoint() {
  12.         add_rewrite_endpoint( 'premium-support', EP_ROOT | EP_PAGES );
  13.     }
  14.     add_action( 'init', 'bbloomer_add_premium_support_endpoint' );
  15.     // ——————
  16.     // 2. Add new query var
  17.     function bbloomer_premium_support_query_vars( $vars ) {
  18.         $vars[] = 'premium-support';
  19.         return $vars;
  20.     }
  21.     add_filter( 'query_vars', 'bbloomer_premium_support_query_vars', 0 );
  22.     // ——————
  23.     // 3. Insert the new endpoint into the My Account menu
  24.     function bbloomer_add_premium_support_link_my_account( $items ) {
  25.         $items['premium-support'] = '联系我们';
  26.         return $items;
  27.     }
  28.     add_filter( 'woocommerce_account_menu_items', 'bbloomer_add_premium_support_link_my_account' );
  29.     // ——————
  30.     // 4. Add content to the new endpoint
  31.     function bbloomer_premium_support_content() {
  32.     echo '

    联系我们

     

    有任何问题,欢迎与站长Qi取得联系。Qi的QQ号:xxxxxx,微信号:xxxxx。添加好友请注明“店铺订单”字样。更多的联系方式在:。

    '

    ;
  33.     // echo do_shortcode( ' /* your shortcode here */ ' );
  34.     }
  35.     add_action( 'woocommerce_account_premium-support_endpoint', 'bbloomer_premium_support_content' );
  36.     // Note: add_action must follow 'woocommerce_account_{your-endpoint-slug}_endpoint' format

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

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

收藏

本文由 云模板 作者: 发表,转载请注明来源!

 

也想出现在这里?吧

发表评论

热销模板

本站承接 WordPress / PbootCMS / DedeCMS 等

系统建站、仿站、开发、定制等业务!

由 提供技术支持!


提交需求或反馈

Demand feedback