Skip to main content
Easily create better & faster websites with the Total WordPress Theme Learn More
(opens a new tab)
Tutorials

The Ultimate List of WooCommerce Code Snippets

Times flies… It’s been 6 months since I started to work for WooThemes as a WooCommerce full time support technician. During these 6 months I learnt a lot on WooCommerce and I coded a lot of WooCommerce related snippets.

WooCommerce is really powerful tool and easily expandable. It has many hooks that can be used for nearly everything, and that’s what make WooCommerce so good. Here is a list of snippets I wrote or adapted during the past months.

The following snippets can be copied and pasted into your theme’s functions.php folder (a child theme if working with a 3rd party theme) or via a code snippet plugin.

I’ve gone ahead and numbered all the snippets so if you have any issues with a specific one you can let me know in the comments section! WooCommerce does make frequent updates and it’s possible some of these snippets may need updating in the future.

Also here is a table of contents if you want to quickly jump to view a specific snippet:

Table of contents

1. Declare WooCommerce Support

This snippet can be added to your theme to let WooCommerce know it’s compatible.

add_action( 'after_setup_theme', function() {
    add_theme_support( 'woocommerce' );
} );

2. Remove All WooCommerce CSS

This snippet will remove all the WooCommerce stylesheets so you have full control over the design.

add_filter( 'woocommerce_enqueue_styles', '__return_empty_array' );

3. Remove Specific WooCommerce Styles

This snippet will remove specific WooCommerce stylesheets:

function wpexplorer_wc_remove_styles( $styles ) {
    unset( $styles['woocommerce-general'] );
    unset( $styles['woocommerce-layout'] );
    unset( $styles['woocommerce-smallscreen'] );
    return $styles;
}
add_filter( 'woocommerce_enqueue_styles', 'wpexplorer_wc_remove_styles' );

This snippet will enable support for the product gallery slider, zoom and lightbox.

add_action( 'after_setup_theme', function() {
    add_theme_support( 'wc-product-gallery-slider' );
    add_theme_support( 'wc-product-gallery-zoom' );
    add_theme_support( 'wc-product-gallery-lightbox' );
} );

5. Add Payment Type to WooCommerce Admin Email

This snippet will display the payment type that was used at checkout in the order email.

function wpexplorer_wc_add_payment_method_to_admin_new_order( $order, $is_admin_email ) {
	if ( $is_admin_email ) {
		echo '<p><strong>Payment Method:</strong> ' . esc_html( $order->payment_method_title ) . '</p>';
	}
}
add_action( 'woocommerce_email_after_order_table', 'wpexplorer_wc_add_payment_method_to_admin_new_order', 15, 2 );

6. Up-Sells Products Display Count

This snippet will modify how many up-sell products display, changing it to 3.

remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_upsell_display', 15 );

if ( ! function_exists( 'woocommerce_output_upsells' ) ) {
	function woocommerce_output_upsells() {
		woocommerce_upsell_display( 3,3 );
	}
}
add_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_upsells', 15 );

7. Remove Specific Product Categories from Shop Page

This snippet can be used to exclude products in specific categories from the shop.

function wpexplorer_exclude_categories_from_shop( $query ) {
	if ( ! $query->is_main_query() || is_admin() || ! function_exists( 'is_shop' ) || ! is_shop() ) {
		return;
	}

	$excluded_categories = [
		'color',
		'flavor',
		'spices',
		'vanilla',
	];
 
	$query->set( 'tax_query', [ [
		'taxonomy' => 'product_cat',
		'field'    => 'slug',
		'terms'    => $excluded_categories,
		'operator' => 'NOT IN'
	] ] );
}
add_action( 'pre_get_posts', 'wpexplorer_exclude_categories_from_shop' );

8. Quickly Translate Any String

Sometimes you may want to quickly translate a string without having to mess with the POT files. This snippet can be used to modify any translatable text.

function wpexplorer_translate_text( $text ) {
	$text = str_replace( 'Choose and option', 'Select', $text );
	return $text;
}
add_filter( 'gettext', 'wpexplorer_translate_text' );
add_filter( 'ngettext', 'wpexplorer_translate_text' );

9. Exclude a Category from the WooCommerce Categories Widget

This snippet can be used to remove certain categories from the WooCommerce categories widget. Be sure to change [ '16' ] to be an array of the term ID’s you wish to exclude.

function wpexplorer_filter_wc_categories_widget_args( $args ) {
	$args['exclude'] = [ '16' ];
	return $args;
}
add_filter( 'woocommerce_product_categories_widget_args', 'wpexplorer_filter_wc_categories_widget_args' );

10. Modify the “Out of Stock” Text

The following snippet will modify the default “Out of Stock” text and change it to “Sold”.

function wpexplorer_wc_modify_out_of_stock_text( $availability ) {
	$availability['availability'] = str_replace( 'Out of stock', 'Sold', $availability['availability'] );
	return $availability;
}
add_filter( 'woocommerce_get_availability', 'wpexplorer_wc_modify_out_of_stock_text' );

11. Display “Product Already in Cart” Instead of “Add to Cart” Button

This snippet to change the default “Add to Cart” button to “Already in cart – Add Again? when viewing a product that’s already in the cart.

// Modify the WooCommerce single product add to cart text.
function wpexplorer_wc_modify_add_to_cart_text( $text ) {
	global $woocommerce;
	foreach( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
		if ( $values['data']->id == get_the_ID() ) {
			$text = esc_html__('Already in cart - Add Again?', 'text_domain' );
			break;
		}
	}
	return $text;
}
add_filter( 'woocommerce_product_single_add_to_cart_text', 'wpexplorer_wc_modify_add_to_cart_text' );

// Modify the WooCommerce entry add to cart text.
function woo_archive_custom_cart_button_text( $text ) {
	global $woocommerce;
	foreach( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
		if ( $values['data']->id == get_the_ID() ) {
			$text = esc_html__('Already in cart - Add Again?', 'text_domain' );
			break;
		}
	}
	return $text;
}
add_filter( 'add_to_cart_text', 'woo_archive_custom_cart_button_text' );

12. Hide the Category View Products Count

This snippet will remove the default products count in the categories view.

add_filter( 'woocommerce_subcategory_count_html', '__return_empty_string' );

13. Make Account Checkout Fields Required

This snippet will add the required attribute to various checkout fields.

function wpexplorer_wc_filter_checkout_fields( $fields ) {
	$fields['account']['account_username']['required'] = true;
	$fields['account']['account_password']['required'] = true;
	$fields['account']['account_password-2']['required'] = true;
	return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'wpexplorer_wc_filter_checkout_fields' );

14. Rename a Product Tab

This snippet will rename the product “description” tab to “More Info”. You can modify the code to target any tab.

function wpexplorer_wc_filter_product_tabs( $tabs ) {
	$tabs['description']['title'] = 'More info';
	return $tabs;
}
add_filter( 'woocommerce_product_tabs', 'wpexplorer_wc_filter_product_tabs', 100 );

15. List WooCommerce Product Categories

This snippet will grab the product categories, loop through them and display them as a list.

$product_categories = get_terms( 'product_cat', [
	'number'     => '3',
	'orderby'    => 'name',
	'order'      => 'ASC',
	'hide_empty' => true
] );

if ( $product_categories && ! is_wp_error( $product_categories ) ) {
	echo "<ul>";
	foreach ( $product_categories as $product_category ) {
		echo '<li><a href="' . esc_url( get_term_link( $product_category ) ) . '">' . esc_html( $product_category->name ) . '</li>';  
	}
	echo "</ul>";
}

16. Replace Shop Page Title

This code snippet replaces the default shop page title. Note, that if the code doesn’t work it could be because of the theme you are using.

function wpexplorer_wc_archive_title( $title ) {
    if ( is_shop() && $shop_id = wc_get_page_id( 'shop' ) ) {
        $title = get_the_title( $shop_id );
    }
    return $title;
}
add_filter( 'get_the_archive_title', 'wpexplorer_wc_archive_title' );

17. Change a Widget Title

This snippet will allow you to modify a widget title (on demand).

function wpexplorer_wc_widget_title( $title, $instance, $id_base ) {
	if( 'onsale' === $id_base ) {
		return 'Custom Onsale Widget Title';
	}
	return $title;
}
add_filter( 'widget_title', 'wpexplorer_wc_widget_title', 10, 3 );

This snippet will return a list of featured product ID’s.

$query_featured_products = new WP_Query( [
	'post_type'           => 'product',
	'ignore_sticky_posts' => true,
	'posts_per_page'      => -1,
	'fields'              => 'ids',
	'tax_query'           => [
		'taxonomy' => 'product_visibility',
		'field'    => 'name',
		'terms'    => 'featured',
		'operator' => 'IN'
	]
] );
$featured_products = $query_featured_products->posts ?? [];

19. Set a Minimum Order Amount

This snippet will add a minimum order amout of 5 so the user can’t check out unless they have at least 5 items in the cart.

function wpexplorer_wc_minimum_order_amount() {
	global $woocommerce;
	$minimum = 5;
	if ( $woocommerce->cart->total() ) {
		add_error( sprintf( 'You must have an order with a minimum of %s to place your order.', $minimum ) );
	}
}
add_action( 'woocommerce_checkout_process', 'wpexplorer_wc_minimum_order_amount' );

20. Modify the Default Shop Catalog Orderby

This snippet will modify the default order of products shown in your shop. Note, you can now set this via WooCommerce settings instead.

function wpexplorer_wc_default_catalog_orderby() {
	return 'price';
}
add_filter( 'woocommerce_default_catalog_orderby', 'wpexplorer_wc_default_catalog_orderby' );

21. Redirect Add to Cart Button to Checkout Page

This snippet will redirect users to the checkout when adding a product to the cart. Note, you can do this via the WooCommerce settings now without any custom code.

function wpexplorer_wc_redirect_to_checkout( $redirect ) {
	if ( $checkout_url = wc_get_checkout_url() ) {
		$redirect = $checkout_url;
	}
	return $redirect;
}
add_filter( 'add_to_cart_redirect', 'wpexplorer_wc_redirect_to_checkout' );

22. Add Email Recipient When Order is Completed

This snippet allows you to add extra email recipients to receive the completed order email.

function wpexplorer_wc_add_email_recipients( $recipient ) {
	$recipient = "{$recipient}, your@email.com";
	return $recipient;
}
add_filter( 'woocommerce_email_recipient_customer_completed_order', 'wpexplorer_wc_add_email_recipients', 10 );

This snippet will allow you to modify the default PayPal logo on the check out form.

function wpexplorer_wc_replace_paypal_icon() {
	return 'https://www.paypalobjects.com/webstatic/mktg/logo-center/logo_betalen_met_paypal_nl.jpg';
}
add_filter( 'woocommerce_paypal_icon', 'wpexplorer_wc_replace_paypal_icon' );

24. Modify the Default Placeholder Image

This snippet will modify the default placeholder image.

function wpexplorer_wc_change_placeholder_image( $src ) {
	$src = "YOUR_CUSTOM_IMAGE_URL";
	return $src;
}
add_filter( 'woocommerce_placeholder_img_src', 'wpexplorer_wc_change_placeholder_image' );

25. Manually Empty the Cart

This code snippet will manually empty your cart.

global $woocommerce;
$woocommerce->cart->empty_cart(); 

26. Add a Product to the Cart on Page Load

This snippet will automatically add a product to the cart when visiting the site.

function wpexplorer_wc_auto_add_products_to_cart() {
	if ( ! is_admin() ) {
		global $woocommerce;
		$product_id_to_add = 64; // ID of product to add
		$found = false;
		foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
			if ( (int) $product_id_to_add === (int) $values['data']->id ) {
				$found = true;
				return;
			}
		}
		if ( ! $found ) {
			$woocommerce->cart->add_to_cart( $product_id_to_add );
		}
	}
}
add_action( 'init', 'wpexplorer_wc_auto_add_products_to_cart' );

27. Add a Custom Currency Symbol

This snippet will add a new currency symbol that you can select from.

// Adds a custom currency.
function wpexplorer_wc_add_custom_curency( $currencies ) {
	$currencies['ABC'] = __( 'ABC Currency Name', 'text_domain' );
	return $currencies;
}
add_filter( 'woocommerce_currencies', 'wpexplorer_wc_add_custom_curency' );

// Adds a custom currency symbol.
function wpexplorer_wc_modify_currency_symbol( $currency_symbol, $currency ) {
	if ( 'ABC' === $currency ) {
		$currency_symbol = '$';
	}
	return $currency_symbol;
}
add_filter( 'woocommerce_currency_symbol', 'wpexplorer_wc_modify_currency_symbol', 10, 2 );

28. Modify the Add to Cart Button Text

This snippet will change the default Add to Cart button text to your custom text. Note, it will affect all buttons regardless of the product type.

function wpexplorer_wc_modify_cart_button_text() {
	return __( 'My Button Text', 'text_domain' );
}
add_filter( 'single_add_to_cart_text', 'wpexplorer_wc_modify_cart_button_text' );
add_filter( 'add_to_cart_text', 'wpexplorer_wc_modify_cart_button_text' );

29. BCC all WooCommerce Emails

If you wish to bcc all emails you can do so with the following snippet:

function wpexplorer_wc_bcc_all_emails() {
	return 'Bcc: youremail@yourdomain.com' . "\r\n";
}
add_filter( 'woocommerce_email_headers', 'wpexplorer_wc_bcc_all_emails' );

This snippet can be used to modify the default number of related products that display on the single product pages.

function wpexplorer_wc_related_posts_per_page( $args ) {
    $args['posts_per_page'] = 4;
    return $args;
}
add_filter( 'woocommerce_output_related_products_args', 'wpexplorer_wc_related_posts_per_page' );

31. Change the Next and Previous Text into Arrows

This snippet hooks into the WooCommerce pagination arguments to turn the next and previous text into arrows.

function wpexplorer_wc_pagination_args( $args ) {
    $args['prev_text'] = '←';
    $args['next_text'] = '→';
    return $args;
}
add_filter( 'woocommerce_pagination_args', 'wpexplorer_wc_pagination_args' );

32. Remove all Single Product Tabs

This snippet will quickly remove all tabs from the single product.

add_filter( 'woocommerce_product_tabs', '__return_empty_array', PHP_INT_MAX );

33. Remove Breadcrumbs

This snippet will remove the WooCommerce breadcrumbs.

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

34. Restrict Shipping Countries List

This snippet will restrict the countries in the shipping select dropdown.

function wpexplorer_wc_override_checkout_fields( $fields ) { 
	$fields['shipping']['shipping_country'] = [
		'type'      => 'select',
		'label'     => esc_html__( 'My New Country List', 'text_domain'),
		'options' 	=> [
			'AU' => 'Australia',
		],
	];
	return $fields; 
}
add_filter( 'woocommerce_checkout_fields' , 'wpexplorer_wc_override_checkout_fields' );

35. Change the “Free!” Text on Free Products

This snippet will allow you to modify the default HTML added for free products to let the user know it’s free.

function wpexplorer_wc_modify_free_price_html() {
	return "This product is FREE!";
}

add_filter( 'woocommerce_free_price_html', 'wpexplorer_wc_modify_free_price_html' );

36. Remove All Shipping Methods if Free Shipping is Available

This snippet will remove all available shipping methods if free shipping is available so it’s the only one that can be selected.

function wpexplorer_wc_modify_available_shipping_methds( $available_methods ) {
	if ( isset( $available_methods['free_shipping'] ) ) {
		$available_methods = [ $available_methods['free_shipping'] ];
	}
	return $available_methods;
}
add_filter( 'woocommerce_available_shipping_methods', 'wpexplorer_wc_modify_available_shipping_methds' , 10 );

37. Make the Shipping State Field Not Required

This code snippet will remove the required attribute from the shipping state field.

function wpexplorer_wc_make_shipping_state_not_required( $address_fields ) { 
	$address_fields['shipping_state']['required'] = false;
	return $address_fields;
}
add_filter( 'woocommerce_shipping_fields', 'wpexplorer_wc_make_shipping_state_not_required', 10 );

38. Programmatically Create a New Coupon

This snippet will allow you to insert a new coupon using code.

$coupon_code   = 'UNIQUECODE';
$amount        = '10';
$discount_type = 'fixed_cart';

$new_coupon_id = wp_insert_post( [
	'post_title'   => $coupon_code,
	'post_content' => '',
	'post_status'  => 'publish',
	'post_author'  => 1,
	'post_type'    => 'shop_coupon'
] );

if ( $new_coupon_id ) {
	update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
	update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
	update_post_meta( $new_coupon_id, 'individual_use', 'no' );
	update_post_meta( $new_coupon_id, 'product_ids', '' );
	update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
	update_post_meta( $new_coupon_id, 'usage_limit', '' );
	update_post_meta( $new_coupon_id, 'expiry_date', '' );
	update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
	update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
}

39. Change New Order Email Subject Line

This snippet will allow you to modify the subject of the email sent when a new order is placed.

function wpexplorer_wc_change_new_order_email_subject( $subject, $order ) {
	global $woocommerce;
	$blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
	$subject = sprintf( '[%s] New Customer Order (# %s) from Name %s %s', $blogname, $order->id, $order->billing_first_name, $order->billing_last_name );
	return $subject;
}
add_filter( 'woocommerce_email_subject_new_order', 'wpexplorer_wc_change_new_order_email_subject', 1, 2 );

40. Change the On Sale Text

This snippet will modify the default on sale badge text.

function wpexplorer_woo_sale_flash() {
	return '<span class="onsale">' . esc_html__( 'Sale', 'text_domain' ) . '</span>';
}
add_filter( 'woocommerce_sale_flash', 'wpexplorer_woo_sale_flash' );

Conclusion

And… that’s it! I hope you find will these snippets useful, they were all tested and they all work fine, but if you experience any trouble please let me know  the comments section. Have fun! 😉

Further Reading

You may be interested in the following related WooCommerce guides & articles:

Author Note: This post was originally written by Remi but it’s currently updated and maintained by the WPExplorer staff.

119 Comments
  1. bloorchi · 11 years ago

    Very handy. I think code snippets worth more than a training book.

    • Remi · 11 years ago

      Thanks! 😉

  2. Kamillo · 11 years ago

    Thanks for the snippets but how can i show the custom product variation field at the front-end? From 6 – ADD A CUSTOM FIELD TO A PRODUCT VARIATION

  3. Torsten · 11 years ago

    Code is stripped out 🙁

  4. Bearcat Şándor · 11 years ago

    Thank you very much for these. Not only did post solve a problem i’ve been having, it’s given me a few more ideas for an upcoming project.

    • Remi · 11 years ago

      Thanks!

  5. Tony · 11 years ago

    How can you make the product images bigger on the category pages? as well display more products too. (it currently displays only 10 products per page.)

    Thanks

    • Remi · 11 years ago

      Define custom image size for products or use CSS code! 😉

  6. Brian · 11 years ago

    Thanks for sharing the snippets! Real quick do you have any advice or resources on how to change the layout of the single product page? I’ve been trying to figure out the best practice for moving the entry-summary of a product into a sidebar and just keeping the title image and tabs in the main content area and everything else in a sidebar.

    Thoughts? I’m sure someone has done this but haven’t come across an example yet.

    – Thanks in advance

    • Remi · 11 years ago

      Use custom templates. Basically a custom template allows you to override WooCommerce default files and use your own custom files instead. Here is a quick tutorial that will explain you how to create your custom templates: http://docs.woothemes.com/document/template-structure/

  7. Tony Nguyen · 11 years ago

    Well, I do follow you recently. Really impressive to me. You do work as a Woocommerce just for 6 months? If so, I must confess that you do well. I am also work on online business but I do not have much experience. Love this post. The article is informative. Thanks for sharing. Great job!

    • Remi · 11 years ago

      Hey Tony, many thanks, i’m glad you liked my post, i guess i’ll write another one with new snippets very soon! 😉

  8. Robin · 11 years ago

    Amazing post, very useful thank you Remi!

    Do also have a snippet to place the add to cart button of a specific product anywhere of the page? Maybe also with variations?

    Another interesting one would be to permanently show the add to cart button, even if you have variations.

    • Remi · 11 years ago

      yes i have such a snippet on my website, check it out

  9. Khan · 11 years ago

    Great work mate. I was wondering if we could display “SOLD” under the product image on shop page of all sold items and new visitor could see all sold items. Is there anyway we can create markdown sale on all products in one go (best example would be markdown sale option in eBay stores).

    • Khan · 11 years ago

      I found following code

      $link[‘label’] = apply_filters( ‘not_purchasable_text’, __( ‘Read More‘, ‘woocommerce’ ) );
      which displays sold items on shop page. I want to change text from “Read More” to “SOLD”

      I know, I can change it in woocommerce.css file but I would like to change it in child theme’s .css or functions.php file.

      Could you please help to solve this issue.

  10. Kamillo · 11 years ago

    Thanks for your answer but I didn’t know how to get the variable variation id. Can you please write a example?

    • Samantha · 11 years ago

      Hi, Remi or Kamillo – did you find a solution for this – I’ve been searching everywhere to find a way to add the custom field to each variation, save it with variation data, and be able to retrieve it in my product detail page.
      Would be great if anyone could help.
      Thanks

  11. Robin · 11 years ago

    Hi Remi,
    just used the side-wide search but couldn’t find anything related to showing add to cart button with variations drop-down.

    WooCommerce has a shortcode for showing just the add to cart button with price: [add_to_cart id=”99″] (http://docs.woothemes.com/document/woocommerce-shortcodes/#section-3)

    Unfortunately, it doesn’t work with variations. Any ideas?

  12. Sean · 11 years ago

    Hi, just came across your blog today but a few questions if anyone has some time. With #8, is there any way to make it work with Product Variations, so that if one variation is added to the Cart, the button says “Already in Cart” (as given in the code) but if you select the second product variation, it switches back to “Add to Cart”?

    In other words, you have a Shirt with Red and Green options. If you add the Red Shirt to the cart, the button should change but when you go back and select the Green shirt, it should not say that the product is already in the Cart.

    Second question, would you have any code snippets to allow the customer to select how many products they want shown on the Shop Page or even after a Search is returned. I know you can edit this manually to say 12 products but if the customer wanted to view 24, 36 or All Results on one page, is there any code that allows the user to select these options?

    Last question, is it possible to disable the “click option of the product preview image” on a Single Product page at a “Product by Product” level or even a “Category” level. I realize you can disable the Lightbox but when you click the image, it still opens a tab with the image of the product. So I wanted to know if I can disable this “click” so that nothing registers but I still want to keep the click on for certain products. For example with Virtual Products, I might use a product placeholder and clicking on that product image is of no use to the customer. However, if I have a physical product then yes I would want the customer to click the Lightbox and see more pictures of the product.

    Any help or pointers in the right direction would be appreciated.

  13. Todd McKellips · 11 years ago

    I’d like to setup two different menus for my widget area on my woocommerce pages, for two different department categories? Any suggestions? can I place a line of code in functions.php to say on Category (blue) to show a different “template page” or widget area?

  14. S · 11 years ago

    Hi, thanks a lot for this post, amazing! One quick question: Will these adjustments disappear if I update Woocommerce? Cheers

    • Remi · 11 years ago

      Nop!

  15. Dave · 11 years ago

    Hi there!
    I’m not a PHP guy, but I am a web designer with emphasis on the design aspect of it.
    My question is on #6.
    All I want is a field where the customer can enter personalized text for the product. I know that’s a premium add on through Woo but I hardly think it’s worth the $45. Especially for a site that is only selling one product. Will that do it?
    Also, I copied the code and pasted it at the end of the functions.php file. I don’t see any difference. Where should that show up in the Admin area?
    Sorry for my ignorance.
    Thanks!

  16. AnnaSkye · 11 years ago

    Very helpful. Thanks! I was able to change my add to cart button text.

  17. Chris · 11 years ago

    Is there a snippet to add product colors under each product on the shop page?

    Im using a plugin to make the colors show on the single product page but would love to have a mini version of those color boxes under each product on the shop page.

  18. Tanvir · 11 years ago

    I am trying #5, but no luck there. I tried changing the array field with product category id but doesn’t work. Could you help, please?

  19. Tanvir · 11 years ago

    It works when I am not using dropdown option. But i was wondering if it was possible with dropdown option.

    Thanks
    Tanvir

  20. ocolson · 11 years ago

    Thanks for all the info. You would not happen to have some code to remove the return to shop button from the empty cart.

  21. rosae · 11 years ago

    Is there any way to make visible the cart to a particular product category and not visible in the other categories? Thank you

  22. Sean B · 11 years ago

    Hello, this is with respect to Product Add Ons. Would you know if it is possible to save the content of a form so that when the user leaves the page and comes back, they do not have to fill out the information again? So for example they come to the product page, choose “option A”, “option B” and “enter a message in the text box.”

    They click on Add to Cart but then realize they have to edit their entry. So when I hit the back button, I realize that contents of the form are cleared and I have to make the selections again. How do I store the selections, so that the user can edit what they previously entered?

  23. Jeremy P · 11 years ago

    Any idea how to exclude a category from the “Top Rated Products” widget? I tried modifying some of your code (ie: exclude category from category widget), but couldn’t get it to work. Thanks!

  24. Hang Pham · 11 years ago

    I really very like a list 25 Best WooCommerce Snippets For WordPress. I follow and read a lot of posts on your site and get many tips for me. Thanks for sharing this article. Look forward to hearing more information from you!

  25. rwilk · 11 years ago

    thanks for posting these. looks like some very useful tips!

  26. Matt Conkle · 11 years ago

    Thank you for Number 13! The only thing is for me if you returned nothing, then no title was shown, so I just did an else statement:

    add_filter( ‘woocommerce_page_title’, ‘woo_shop_page_title’);
    function woo_shop_page_title( $page_title ) {
    if($page_title == “Shop”) {
    return “”;
    }else{
    return $page_title;
    }
    }

    and everything worked perfectly. Much appreciated!

  27. John Langlois · 11 years ago

    I really appreciate the snippets you have provided.

    Rather than creating a page for each category that contains the category shortcode, such as [product_categories number=”17″ columns=”3″], I would like to pass the category number via a menu link.
    That way one page can service any category.

    Is this possible through the menu or a filter?

    Thanks.

  28. Gregory Karpinsky · 11 years ago

    add_filter( ‘woocommerce_default_address_fields’,
    function ( $fields ) {
    $fields[‘state’][‘required’] = false;
    return $fields;
    }
    );

  29. Jerry Svensson · 11 years ago

    thanks! a few of them was very useful for me. One question, i use a shortcode for displaying recent products on my homepage, and i need to exclude one category. Do you have any pointers for achieving this? The shortcode i use is

    Thanks!

  30. mayank · 11 years ago

    thanks for this great content i want to ask that #offtopic how to remove my wootheme logo which says powered by wootheme.
    thank you

    • Remi · 11 years ago

      Use a CSS snippet with display: none;

  31. Khan · 11 years ago

    Thanks Remi, Great work. Could you please write a snippet to change “READ MORE” text in product listings. Add to Cart text replaced by Read More for all sold out items and I would like it to display as SOLD. Please help

  32. Justin · 11 years ago

    These are useful codes Remi, Thanks a lot. Is there an extensive list of woocommerce order replacement codes we can use in the email templates to pull in customer and order information? From the templates I’ve been able to figure out that %o pulls in the order id and %s pulls in the blog name. Is there one for first name and last name etc, this would really be good to personalise the emails sent to clients a bit more.

  33. gr3gyp00h · 11 years ago

    Great stuff Remi!
    Consider Part I && Part II bookmarked =)

  34. Stéphane Bergeron · 11 years ago

    Hi Remi,

    Thank you for this wonderful ressource! I have a couple questions regarding changing the add to cart button texts.

    For one thing, I’ve been testing WooCommerce 2.1 beta 2 on a dev site in preparation for a project I’ll start next week. I tried the code you supplied but it’s having no effect whatsoever. I have other filters working so I was wondering if you know if either the filter names for modifying add to cart button text changed in 2.1 or if there’s a bug that should be fixed before final.

    I also found some code in the WC docs that uses different filters that do work:

    http://docs.woothemes.com/document/change-add-to-cart-button-text/

    woocommerce_product_single_add_to_cart_text
    woocommerce_product_add_to_cart_text

    Secondly and related to the working filters just above, there’s usually at least 2 types of add to cart buttons, “Add to Cart” for simple products and “Select Options” for variable products. If I want to target one or the other, do you know the conditional that can be used in the filter function?

    Thanks again! I recently discovered your site as an awesome WooCOmmerce ressource. You do great work here! 🙂

  35. kristina · 11 years ago

    Hi! I was looking for how to remove category for a long time, thanks for that, and small question, how to remove a few categories?

  36. Ching · 11 years ago

    Thanks for the snippets… Do you know how to remove “add to cart” button and make it like “Call for Price”..and Also change “Free” in products that has a 0 price? Thank you!

  37. Tom · 11 years ago

    Hi Remi!

    In respect to #3 – REMOVE PRODUCT CATEGORIES FROM SHOP PAGE

    …Is there a way rather than having ALL products listed on the SHOP base page, to tweak it to just a few catagories? E.g show 4 feature products, 4 newly added products and 4 best selling products on each line?

    Thanks!

  38. Sue Surdam · 11 years ago

    I tried number 23 – Order by date on shop page. Oddly enough it returned the sort by newness on the shop page when I was logged in and when I was logged out it went to sort by default but did not sort by date. Any thoughts on why I am achieving different results when logged in?

    • AJ Clarke · 11 years ago

      Are you using any caching plugins? If so, clear your cache.

  39. Usman · 11 years ago

    Hi,

    I want to this type look of my main page… as is it possible so pls share me… I want main page similar to qeemat.com

    1st Latest Mobile Category
    2nd Latest Laptop Category
    3rd Latest Tablet Category

    etc etc….

  40. ukmbelajar · 11 years ago

    Hi Remi,
    Great snippets.
    I was looking certain snippets related to coupon use. But I see that there are only a few (if not none) that change the behaviour or placement of the coupon entry box.
    Is it difficult, or woocommerce doesn’t have hooks for coupon box, or is it just no one is interested to change the coupon box?

    Do you have a snippets to make the coupon code as required? I don’t use (bypass) the cart so this will only applied to the checkout page.

    Other thing is how to keep payment method displayed and applied when user use a coupon with 100% discount?
    I learned that woocommerce logic is that when the discount is 100% means a payment method is not important anymore. But I think, especially for manual payment, it is still relevant because we want to know which method is prefered by user.
    I also use a snippet to change the order status to complete only on one payment method. Since it is bypassed when using 100% discount, the status is not changed.

    I really hope you have the solution for this.
    Thank you

    Rio

  41. Aleš · 11 years ago

    Hello and thanks very much for these. I was wondering do you have a way to rename the “Products” breadcrumb to something else? It says HOME | PRODUCTS | ITEM1, and I would like it to say HOME | SHOP| ITEM1. Thanks so much and have a nice day

  42. Aleš · 11 years ago

    thank you for your reply. I have Breadcrumb NavXT, so these don’t work. Do you have a way for Breadcrumb NavXT? Thank you very much

    • AJ Clarke · 11 years ago

      Nope, I don’t use the plugin sorry. I use a custom breadcrumbs plugin I developed for myself 😉

  43. Baltasar · 11 years ago

    Apart from these useful code snippets, the WooCommerce Poor Guys Swiss Knife Plugin, offers a set of tools to customize and enhance a WooCommerce instance. It allows to to manage and customize checkout forms, minimum and maximum settings for products and cart and a lot more.

    • AJ Clarke · 11 years ago

      Cool looking plugin, thank you for sharing Baltasar!

  44. Adso da Melk · 11 years ago

    Hello,
    I am looking for a method to hide/disable/ products with blank or zero price.

    After an automatic import I sometimes have a bunch of products with no price that I’d like to not be shown unless another import sets the correct value.

  45. KB · 11 years ago

    Excellent tips.. Thank you very much.

    What’s a good way to change ‘Add to Cart’ to ‘Go to Product’ if the product has already been purchased?

  46. Faroeq · 11 years ago

    Hi,

    Is there a snippet to EMPTY CART AUTOMATICALLY everytime someone leaves checkout page. This is because I want guests to only be able to buy one product at a time and see the summary of one product only.

    Thanks for your help.

  47. Sergio · 11 years ago

    Hi! great and useful post! thank you very much!
    Could I make a question? I need to show a number with the products on sale, something like “15 products of 50 on sale”. Is there a snippet for this?
    thank you very much!

    • AJ Clarke · 11 years ago

      This is actually on the post, have a look at snippet 21 – HAVE ONSALE PRODUCTS.

  48. Sergio · 11 years ago

    ups! so sorry! thank you very much!!!

  49. Bruno S. · 11 years ago

    Thank you & nice work !

    For your first snippet I can’t adapt the code to coupon.

    Do you have a trick ?

  50. Venkatesh · 11 years ago

    hi,

    Woocommerce theme by default hides “Options values & Grand Total value” if option values are 0. Is it possible not to remove these divs, if value even 0?

    Thanks

  51. riverfoot · 11 years ago

    Hey, you seem like you know your WooCommerce!
    I have been struggling with this lately, maybe you could help point me in the right direction?

    I am trying to change the add to cart button to remove from cart if it has already been added to cart.

    Any ideas? Thanks for the sweet blog!

  52. Ravenous Raven Design · 11 years ago

    12 – LIST WOOCOMMERCE PRODUCT CATEGORIES
    This code did not work for me. It actually broke my website 🙁

    • Remi · 11 years ago

      make sure you embed the code between PHP tags, that’s a common mistake when copying code

  53. Dhruba Tamuli · 11 years ago

    Hi Remi,
    Do you have any tips to shorten (truncate) long products title in WooCommerce shop pages?
    Regards,
    Dhruba

  54. Charly · 11 years ago

    Regarding #3: I’ve tried to accomplish this now for about 3 weeks. Trying so many different ways with no joy. I guess I’m not filling in what I’m supposed to correctly, but I’m not a coder and new to WP/WooCommerce. The only thing keeping me from going live is to remove just 1 category from showing on my shop page. 🙁 Can you please help me out?

  55. Heather · 11 years ago

    Hi! I have used your code “8 – Display “product already in cart” instead of “add to cart” button” with woocommerce 2.0.20 and it was GREAT, worked just fine. I updated yesterday to woocommerce 2.1 and it is no longer working…
    Do you know why this might be??
    THANKS! 🙂

    • AJ Clarke · 11 years ago

      Looks like they changed the filter name so it has a prefix (as it should have been to start with) the new filter look like this:

      add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );
      

      I’ll update the post.

  56. A Devasher · 11 years ago

    Great stuff!

    Would it be too cheeky to ask for one more?

    How does one add a ‘sold out’ badge on a product when it is purchased and runs out of stock instead of ‘out of stock’ which should only be for items that are actually out of stock and have not sold.

    Cheers
    A

    • AJ Clarke · 11 years ago

      I think it would look something like this:

      global $product;
      if ( !$product->is_in_stock() ) {
        // This product is sold out, do stuff
      }
      
  57. alberto · 11 years ago

    Hi, thanks for your tips.

    One question, I would like to know where I have to put this code to override the woocommerce code?

    In my functions.php theme?

    • AJ Clarke · 11 years ago

      Yes in functions.php is fine 😉

  58. Nate · 11 years ago

    I vaguely understand how #6 works but I am not sure what file this goes in. Does it work in functions.php or somewhere else.

    • AJ Clarke · 11 years ago

      Yes you can add it in functions.php. Personally I prefer to make a new file called woocommerce-tweaks.php or something similar (then use require_once() in functions.php to load the file) where I add all my additions, that keeps my theme nice and clean 😉

    • Giovani Faganello · 11 years ago

      For WC 2.1+

      	/* Single */
      	add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );	
      	function woo_custom_cart_button_text() {
      		foreach(WC()-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $values ) {
      			$_product = $values['data'];
      			if( get_the_ID() == $_product-&gt;id ) {
      				return __('On cart', 'woocommerce');
      			}
      		}
      		return __('Add to cart', 'woocommerce');
      	}
      	 
      	/* Archives */
      	add_filter( 'woocommerce_product_add_to_cart_text', 'woo_custom2_cart_button_text' );	
      	function woo_custom2_cart_button_text() {
      		foreach(WC()-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $values ) {
      			$_product = $values['data'];
      			if( get_the_ID() == $_product-&gt;id ) {
      				return __('On cart', 'woocommerce');
      			}
      		}
      		return __('Add to cart', 'woocommerce');
      	}	
      
  59. Bram Floria · 11 years ago

    Remi,

    I’m deploying my first woocommerce sites this month, and your snippet library is going to be very helpful. I’ve got a simple issue for which I’m sure you have a quick fix: First client is using the ‘Name Your Price’ plugin, which works well. Unfortunately, the ‘Add to Cart’ button exists not just on the PRODUCT page, but the product CATEGORY and SEARCH pages as well. Clicking an ‘Add to Cart’ button anywhere other than the product page adds the item to the cart at a value of $0. How do I display the ‘Add to Cart’ button ONLY on the Product page?

  60. Wendy Solum · 11 years ago

    Hello,

    This is a great list of snippets. Thank you! I am looking for something a bit different and wonder if you might share. What I would like to be able to do is to add categories to the shop page drop-down list. I’ve found functions for adding attributes or for sorting categories on the page itself, but I would like the user to be able to choose categories from the drop-down. Is this possible?

    Thank you!

  61. Brenda Scott · 11 years ago

    Great post!! I have bookmarked 1 & 2!

    Is there a way to set it up so that when they click ‘buy now’ on the shop page…that they go directly to PayPal. Id like to bypass the product page and the checkout pages….

    Thank you!

    • AJ Clarke · 11 years ago

      Hi Brenda, yes you can do what you want by following the instructions on their website for setting up Paypal Express.

  62. JIm · 11 years ago

    It would be really useful in the admin email to list the purchased products according to their category, like:

    Sports Equipment
    helmet…[price info]
    ball……..[price info]

    Athletic Wear
    headband…..[price info]
    running shirt [price info]

    and although I didn’t do it above, for each product list to be alphabetized in each category.
    Currently I don’t think the default email echos category at all. In fact what I get is (I think) a list of products in the order that the purchaser added them to the cart.

    Thank you for the great snippets!

  63. Hypnoseausbildung · 11 years ago

    Thanks a lot for the snippets. The problem is, after updating the plugin, all that needs to be done again with accepting unwanted sideffects. 🙁

    • Remi · 11 years ago

      you don’t need to do it again as the snippets must be placed in functions.php. If you use a parent theme and a child theme you can update the plugin and the parent theme without having to re-add the snippets.

  64. Bernard · 11 years ago

    Hello, can someone help how to put all the categories on my homepage without using short codes. Thanks

    • AJ Clarke · 11 years ago

      The easiest would be using the get_terms function.

  65. K4RL_5 · 11 years ago

    Great little bits of code, I’m looking for something similar that I can put in the {theme}/functions.php that will:
    Add the ORDER TIME to:
    1. Customer order confirmation email
    2. New order admin email
    3. Invoice and delivery not printouts using the ‘WooCommerce Print Invoices & Delivery Notes’ plugin.

    Does anyone have some way of doing this?

  66. StrongEagle · 11 years ago

    OK, so here’s a stupid question…but am I placing these snippets in my custom CSS editor, or in a php file somewhere?

    • AJ Clarke · 11 years ago

      They would go in your functions.php file.

  67. Valerie Adler · 11 years ago

    Ahem…yes, I reread the top of the page and saw that. How bashful it made me feel. So sorry! Dare I ask, does it have to be a child theme, or do changes to a functions.php file survive them upgrades?

    • AJ Clarke · 11 years ago

      No worries Valerie, it’s more fun to jump into the code then read the post 😉 It’s always best to use a child theme. However, if this is your personal site lets say and you’ll never be changing the theme because you made it, then it’s fine to add it to the parent them. If you think one day you’ll switch themes or your aren’t the developer and might have to update in the future then use a child theme.

  68. AlexB · 11 years ago

    Do you know if there is a way to hide products after a specific date? We sell tickets to trips and have a cutoff date 3-4 days prior to the trip.

    • AJ Clarke · 11 years ago

      I’m not sure if there is any way of doing this. This is not really a WooCommerce snippet but more of a WordPress snippet (auto drafting/deleting posts). There is a plugin out there called “Post Expirator” I haven’t tested it myself, but might be worth checking out.

  69. nickthelewNick · 11 years ago

    Hi there,

    Can anyone help on snippets/code to change the default titles of the woocommerce Billing Address / Shipping Address as it appears site wide? We need to edit them but cannot find anything on how to do so anywhere!! Tried a couple of things with using child theme but this does not change them site wide.

    Any ideas? Would be greatly appreciated! Thanks!

  70. Damien O'Neill (@damo3000) · 11 years ago

    Hey Remi, cool post, I really liked it!

    Just a question though, would you know if there is a way of changing the Price label to display “Out of Stock” when there is currently no stock available?

    Cheers

    Damien

  71. Alan Chua · 11 years ago

    Hi Remi,

    Is there any code to show add to cart to product listing? E.g I have a product category selling routers, and when user click on this category, the list of routers appear and I would like to have an add to cart (as an option) instead of user having to go in to detail in order to add to cart.

    Thanks

  72. Hai Bang Doan · 11 years ago

    Hi everyone.Can anyone help on snippets/code to rename last name,firstname,phone label and free shipping in check out page.Thank you so much!

    • AJ Clarke · 11 years ago

      Have a look at the previous comment, how to change the checkout fields are fully documented on the WooThemes site (link above).

  73. Andjjs · 11 years ago

    Thank you for all you snippets. Many will be very helpful. I have one question. Do you think it would be possible to change “Restrict shipping countries list” snippet to “Restrict shipping STATES list”? Kind regards

  74. hoadiepdo99201 · 11 years ago

    I want to get total order of a product by product id in this month, or date?
    Can you help me

  75. mehmoodkhan951Mehmoo · 11 years ago

    Awesome post really like it.. I am a WordPress Developer…

  76. Sherri@HuttoWebServices · 11 years ago

    This is SO helpful – THANKS!

    • Remi · 11 years ago

      Thanks! 😉

  77. kcullinan · 11 years ago

    I couldn’t get #3 (remove categories from product page) to work… did anyone else have a problem? I put it in my funtions.php and used the slug names to try and remove a few categories but they never left…

    • AJ Clarke · 11 years ago

      This is to remove products in certain categories from your main products archive (not singular product post). If you are aware of this and it’s not working for you, make sure you aren’t using the WooCommerce shortcode or your theme isn’t overriding the default archive. This will only work if you are on the products archive page and also if it’s defined as the shop in the WooCommerce settings.

      ps: I noticed Remi also added “! is_user_logged_in()” so it won’t work if you are logged in either. I’m not sure why he added this, my guess is for debugging purposes.

      • kcullinan · 11 years ago

        AJ, thanks for the clarification. This isn’t what I was looking for. I recently took over managing a friend’s site for her. She originally had some 600+ products and probably 50 categories. She decided she only wanted to display her line of products (<20). I "hid" all of the other products by changing their visibility (just in case she changed her mind later and wanted to bring all of the other products back some day), but the categories don't have an option to hide them. I didn't want to delete them either because those 600+ products are still associated with all of these categories that I don't currently need, and again, should she change her mind, I didn't want to redo all of the work someone already did. So, basically, I was just trying to find a way to hide bunch of categories from the shop without deleting them. If you are anyone else knows a solution for me, i'd be grateful! Thanks again.

        • AJ Clarke · 11 years ago

          When you say hiding the categories from the shop though, do you mean under the product description where it says “Category:”? Or on the page that displays all the categories with a thumbnail? Or on the sidebar category widget? If you can specify, I can provide a solution 😉

          • kcullinan · 11 years ago

            Thanks AJ. If you look here susan-hopkins.com/lifestyle/ you will see the list of categories down the left side. The Blanco theme has an option to turn the categories sidebar on or off but I was hoping to keep it and hide all but a handful of the categories.

            • AJ Clarke · 11 years ago

              Looking at the source code this category widget isn’t a standard WP or WooCommerce widget. You are adding it via a plugin or the theme itself, you should try contacting the Blanco theme developer for assistance or the plugin developer if that widget is being added via a plugin.

              ps: The easiest solution though is for you to just create a new custom menu for your categories at Appearance->Menu and then use the custom menu widget.

              • kcullinan · 11 years ago

                That’s a great idea! Thank you!!

  78. Mentol · 11 years ago

    Hello Remi and thank you for a great set of snippets! I have a question regarding the WooCommerce settings panels:
    – is it possible, and how, to previously define a few of the settings and somehow hide them from the Shop Manager?
    I need to have a few of these already setup by default for the Shop Manager (for instance, don´t activate taxes in the Taxes tab, prices already have tax, etc.) and hide them from him so that he cannot change them.
    Any help is greatly appreciated. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *

Learn how your comment data is processed by viewing our privacy policy here.