25 Best WooCommerce Snippets For WordPress

My 25 Best WooCommerce Snippets For WordPress
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 (read a lot!) of WooCommerce related snippets. Actually, 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; all these snippets must be pasted in the functions.php file within your theme folder:

1 – ADD PAYMENT TYPE TO WOOCOMMERCE ADMIN EMAIL

1 add_action( 'woocommerce_email_after_order_table','add_payment_method_to_admin_new_order', 15, 2 );
2  
3 function add_payment_method_to_admin_new_order( $order$is_admin_email ) {
4   if $is_admin_email ) {
5     echo '<p><strong>Payment Method:</strong> ' $order->payment_method_title .'</p>';
6   }
7 }

2 – UP-SELLS PRODUCTS PER PAGE / PER LINE

1 remove_action( 'woocommerce_after_single_product_summary','woocommerce_upsell_display', 15 );
2 add_action( 'woocommerce_after_single_product_summary','woocommerce_output_upsells', 15 );
3  
4 if ( ! function_exists( 'woocommerce_output_upsells' ) ) {
5     function woocommerce_output_upsells() {
6         woocommerce_upsell_display( 3,3 ); // Display 3 products in rows of 3
7     }
8 }

3 – REMOVE PRODUCT CATEGORIES FROM SHOP PAGE

1 add_action( 'pre_get_posts''custom_pre_get_posts_query' );
2
3 function custom_pre_get_posts_query( $q ) {
4  
5     if ( ! $q->is_main_query() ) return;
6     if ( ! $q->is_post_type_archive() ) return;
7     
8     if ( ! is_admin() && is_shop() && ! is_user_logged_in() ) {
9  
10         $q->set( 'tax_query'array(array(
11             'taxonomy' => 'product_cat',
12             'field' => 'slug',
13             'terms' => array'color''flavor''spices''vanilla' ), // Don't display products in these categories on the shop page
14             'operator' => 'NOT IN'
15         )));
16     
17     }
18  
19     remove_action( 'pre_get_posts''custom_pre_get_posts_query' );
20  
21 }

4 – QUICKLY TRANSLATE ANY STRING

1 add_filter('gettext',  'translate_text');
2 add_filter('ngettext',  'translate_text');
3  
4 function translate_text($translated) {
5      $translated str_ireplace('Choose and option',  'Select',  $translated);
6      return $translated;
7 }

5 – EXCLUDE A CATEGORY FROM THE WOOCOMMERCE CATEGORY WIDGET

1 add_filter( 'woocommerce_product_categories_widget_args','woo_product_cat_widget_args' );
2
3 function woo_product_cat_widget_args( $cat_args ) {
4     
5     $cat_args['exclude'] = array('16');
6     
7     return $cat_args;
8 }

6 – ADD A CUSTOM FIELD TO A PRODUCT VARIATION

1 //Display Fields
2 add_action( 'woocommerce_product_after_variable_attributes''variable_fields', 10, 2 );
3 //JS to add fields for new variations
4 add_action( 'woocommerce_product_after_variable_attributes_js''variable_fields_js');
5 //Save variation fields
6 add_action( 'woocommerce_process_product_meta_variable''variable_fields_process', 10, 1 );
7  
8 function variable_fields( $loop$variation_data ) {
9 ?>  
10     <tr>
11         <td>
12             <div>
13                     <label></label>
14                     <input type="text" size="5" name="my_custom_field[]" value=""/>
15             </div>
16         </td>
17     </tr>
18
19 <tr>
20         <td>
21             <div>
22                     <label></label>
23                     
24             </div>
25         </td>
26     </tr>
27 <?php
28 }
29  
30 function variable_fields_process( $post_id ) {
31     if (isset( $_POST['variable_sku'] ) ) :
32         $variable_sku $_POST['variable_sku'];
33         $variable_post_id $_POST['variable_post_id'];
34         $variable_custom_field $_POST['my_custom_field'];
35         for $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
36             $variation_id = (int) $variable_post_id[$i];
37             if ( isset( $variable_custom_field[$i] ) ) {
38                 update_post_meta( $variation_id'_my_custom_field'stripslashes($variable_custom_field[$i] ) );
39             }
40         endfor;
41     endif;
42 }

7 – REPLACE “OUT OF STOCK” BY “SOLD”

1 add_filter('woocommerce_get_availability''availability_filter_func');
2
3 function availability_filter_func($availability)
4 {
5     $availability['availability'] = str_ireplace('Out of stock''Sold',$availability['availability']);
6     return $availability;
7 }

8 – DISPLAY “PRODUCT ALREADY IN CART” INSTEAD OF “ADD TO CART” BUTTON

1 /**
2  * Change the add to cart text on single product pages
3  */
4 add_filter( 'woocommerce_product_single_add_to_cart_text','woo_custom_cart_button_text' );
5
6 function woo_custom_cart_button_text() {
7
8     global $woocommerce;
9     
10     foreach($woocommerce->cart->get_cart() as $cart_item_key => $values ) {
11         $_product $values['data'];
12     
13         if( get_the_ID() == $_product->id ) {
14             return __('Already in cart - Add Again?''woocommerce');
15         }
16     }
17     
18     return __('Add to cart''woocommerce');
19 }
20
21 /**
22  * Change the add to cart text on product archives
23  */
24 add_filter( 'add_to_cart_text''woo_archive_custom_cart_button_text' );
25
26 function woo_archive_custom_cart_button_text() {
27
28     global $woocommerce;
29     
30     foreach($woocommerce->cart->get_cart() as $cart_item_key => $values ) {
31         $_product $values['data'];
32     
33         if( get_the_ID() == $_product->id ) {
34             return __('Already in cart''woocommerce');
35         }
36     }
37     
38     return __('Add to cart''woocommerce');
39 }

9 – HIDE PRODUCTS COUNT IN CATEGORY VIEW

1 add_filter( 'woocommerce_subcategory_count_html','woo_remove_category_products_count' );
2
3 function woo_remove_category_products_count() {
4     return;
5 }

10 – MAKE ACCOUNT CHECKOUT FIELDS REQUIRED

1 add_filter( 'woocommerce_checkout_fields''woo_filter_account_checkout_fields' );
2  
3 function woo_filter_account_checkout_fields( $fields ) {
4     $fields['account']['account_username']['required'] = true;
5     $fields['account']['account_password']['required'] = true;
6     $fields['account']['account_password-2']['required'] = true;
7
8     return $fields;
9 }

11 – RENAME A PRODUCT TAB

1 add_filter( 'woocommerce_product_tabs''woo_rename_tab', 98);
2 function woo_rename_tab($tabs) {
3
4  $tabs['description']['title'] = 'More info';
5
6  return $tabs;
7 }

12 – LIST WOOCOMMERCE PRODUCT CATEGORIES

1 $args array(
2     'number'     => $number,
3     'orderby'    => $orderby,
4     'order'      => $order,
5     'hide_empty' => $hide_empty,
6     'include'    => $ids
7 );
8
9 $product_categories = get_terms( 'product_cat'$args );
10
11 $count count($product_categories);
12  if $count > 0 ){
13      echo "<ul>";
14      foreach $product_categories as $product_category ) {
15        echo '<li><a href="' . get_term_link( $product_category ) . '">' .$product_category->name . '</li>';
16         
17      }
18      echo "</ul>";
19  }

13 – REPLACE SHOP PAGE TITLE

1 add_filter( 'woocommerce_page_title''woo_shop_page_title');
2
3 function woo_shop_page_title( $page_title ) {
4     
5     if'Shop' == $page_title) {
6         return "My new title";
7     }
8 }

14 – CHANGE A WIDGET TITLE

1 /*
2  * Change widget title
3  */
4 add_filter( 'widget_title''woo_widget_title', 10, 3);
5
6 function woo_widget_title( $title$instance$id_base ) {
7     
8     if'onsale' == $id_base) {
9         return "My new title";
10     }
11 }

15 – REMOVE WOOCOMMERCE DEFAULT SETTINGS

1 add_filter( 'woocommerce_catalog_settings''woo_remove_catalog_options' );
2
3 function woo_remove_catalog_options( $catalog ) {
4
5     unset($catalog[23]); //Trim zeros (no)
6     unset($catalog[22]); //2 decimals
7     unset($catalog[21]); //decimal sep (.)
8     unset($catalog[20]); //thousand sep (,)
9     unset($catalog[19]); //currency position (left)
10     unset($catalog[18]); //currency position (left)
11     unset($catalog[5]); // ajax add to cart (no)   
12     
13     return $catalog;
14 }

16 – CHANGE “FROM” EMAIL ADDRESS

1 function woo_custom_wp_mail_from() {
2         global $woocommerce;
3         return html_entity_decode( 'your@email.com' );
4 }
5 add_filter( 'wp_mail_from''woo_custom_wp_mail_from', 99 );

17 – DECODE FROM NAME IN WOOCOMMERCE EMAIL

1 function woo_custom_wp_mail_from_name() {
2         global $woocommerce;
3         return html_entity_decode( get_option( 'woocommerce_email_from_name' ) );
4 }
5 add_filter( 'wp_mail_from_name''woo_custom_wp_mail_from_name', 99 );
6
7 function woo_custom_wp_mail_from() {
8         global $woocommerce;
9         return html_entity_decode( get_option( 'woocommerce_email_from' ) );
10 }
11 add_filter( 'wp_mail_from_name''woo_custom_wp_mail_from_name', 99 );

18 – RETURN FEATURED PRODUCTS IDS

1 function woo_get_featured_product_ids() {
2     // Load from cache
3     $featured_product_ids = get_transient( 'wc_featured_products' );
4
5     // Valid cache found
6     if ( false !== $featured_product_ids )
7         return $featured_product_ids;
8
9     $featured = get_posts( array(
10         'post_type'      => array'product''product_variation' ),
11         'posts_per_page' => -1,
12         'post_status'    => 'publish',
13         'meta_query'     => array(
14             array(
15                 'key'       => '_visibility',
16                 'value'     => array('catalog''visible'),
17                 'compare'   => 'IN'
18             ),
19             array(
20                 'key'   => '_featured',
21                 'value' => 'yes'
22             )
23         ),
24         'fields' => 'id=>parent'
25     ) );
26
27     $product_ids array_keys$featured );
28     $parent_ids  array_values$featured );
29     $featured_product_ids array_uniquearray_merge$product_ids$parent_ids ) );
30
31     set_transient( 'wc_featured_products'$featured_product_ids );
32
33     return $featured_product_ids;
34 }

19 – ADD CUSTOM FIELD TO EDIT ADDRESS PAGE

1 // add fields to edit address page
2 function woo_add_edit_address_fields( $fields ) {
3
4     $new_fields array(
5                 'date_of_birth'     => array(
6                 'label'             => __( 'Date of birth''woocommerce' ),
7                 'required'          => false,
8                 'class'             => array'form-row' ),
9             ),
10         );
11         
12     $fields array_merge$fields$new_fields );
13     
14     return $fields;
15     
16 }
17
18 add_filter( 'woocommerce_default_address_fields''woo_add_edit_address_fields' );

20 – DISPLAY ONSALE PRODUCTS CATALOG SHORTCODE

1 function woocommerce_sale_products( $atts ) {
2
3     global $woocommerce_loop;
4
5     extract(shortcode_atts(array(
6         'per_page'  => '12',
7         'columns'   => '4',
8         'orderby' => 'date',
9         'order' => 'desc'
10     ), $atts));
11
12     $woocommerce_loop['columns'] = $columns;
13
14     $args array(
15         'post_type' => 'product',
16         'post_status' => 'publish',
17         'ignore_sticky_posts'   => 1,
18         'posts_per_page' => $per_page,
19         'orderby' => $orderby,
20         'order' => $order,
21         'meta_query' => array(
22             array(
23                 'key' => '_visibility',
24                 'value' => array('catalog''visible'),
25                 'compare' => 'IN'
26             ),
27             array(
28                 'key' => '_sale_price',
29                 'value' =>  0,
30                 'compare'   => '>',
31                 'type'      => 'NUMERIC'
32             )
33         )
34     );
35     query_posts($args);
36     ob_start();
37     woocommerce_get_template_part( 'loop''shop' );
38     wp_reset_query();
39
40     return ob_get_clean();
41 }
42
43 add_shortcode('sale_products''woocommerce_sale_products');

21 – HAVE ONSALE PRODUCTS

1 function woo_have_onsale_products() {
2     
3     global $woocommerce;
4
5     // Get products on sale
6     $product_ids_on_sale array_filter( woocommerce_get_product_ids_on_sale() );
7
8     if( !empty$product_ids_on_sale ) ) {
9         return true;
10     else {
11         return false;
12     }
13     
14 }
15
16 // Example:
17 if( woo_have_onsale_products() ) {
18     echo 'have onsale products';
19 else {
20     echo 'no onsale product';
21 }

22 – SET MINIMUM ORDER AMOUNT

1 add_action( 'woocommerce_checkout_process''wc_minimum_order_amount' );
2 function wc_minimum_order_amount() {
3     global $woocommerce;
4     $minimum = 50;
5     if $woocommerce->cart->get_cart_total(); < $minimum ) {
6            $woocommerce->add_error( sprintf( 'You must have an order with a minimum of %s to place your order.' $minimum ) );
7     }
8 }

23 – ORDER BY PRICE, DATE OR TITLE ON SHOP PAGE

1 add_filter('woocommerce_default_catalog_orderby''custom_default_catalog_orderby');
2  
3 function custom_default_catalog_orderby() {
4      return 'date'// Can also use title and price
5 }

24 – REDIRECT ADD TO CART BUTTON TO CHECKOUT PAGE

1 add_filter ('add_to_cart_redirect''redirect_to_checkout');
2
3 function redirect_to_checkout() {
4     global $woocommerce;
5     $checkout_url $woocommerce->cart->get_checkout_url();
6     return $checkout_url;
7 }

25 – ADD EMAIL RECIPIENT WHEN ORDER COMPLETED

1 function woo_extra_email_recipient($recipient$object) {
2     $recipient $recipient ', your@email.com';
3     return $recipient;
4 }
5 add_filter( 'woocommerce_email_recipient_customer_completed_order','woo_extra_email_recipient', 10, 2);

 

*originally posted at http://www.wpexplorer.com/best-woocommerce-snippets/