JoomlaVision > WordPress > 24 Codes You Should Use When Working With WooCommerce

24 Codes You Should Use When Working With WooCommerce

You may have used a lot of beautiful themes, multi-functional plugins for your Woocommerce website. Then you can take advantages of available hooks to customize sites as you want. If you are using Woocommerce, it will be a good idea to have a look at following codes then find which is suitable for your site. How can you use it? Really simple, just copy and paste them into the functions.ph file within the theme you are using.

woocommerce codes

Delete ‘Product’ in the navigation bar

/*
 * Hide "Products" in WooCommerce breadcrumb
 */
function woo_custom_filter_breadcrumbs_trail ( $trail ) {
  foreach ( $trail as $k => $v ) {
    if ( strtolower( strip_tags( $v ) ) == 'products' ) {
      unset( $trail[$k] );
      break;
    }
  }
  return $trail;
}
add_filter( 'woo_breadcrumbs_trail', 'woo_custom_filter_breadcrumbs_trail', 10 ); 

Automatically add accessed products to cart

Replace ‘64’ by the ID of the automatically added products

/*
 * Add item to cart on visit
 */
function add_product_to_cart() {
        if ( ! is_admin() ) {
                global $woocommerce;
                $product_id = 64;
                $found = false;
                //check if product already in cart
                if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
                        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $value
 ) {
                                $_product = $values['data'];
                                if ( $_product->id == $product_id )
                                        $found = true;
                       }
                        // if product not found, add it
                        if ( ! $found )
                                $woocommerce->cart->add_to_cart( $product_id );
                } else {
                        // if no products in cart, add it
                        $woocommerce->cart->add_to_cart( $product_id );
                }
        }
}
add_action( 'init', 'add_product_to_cart' );

Add currency symbol according to your own

add_filter( 'woocommerce_currencies', 'add_my_currency' );
function add_my_currency( $currencies ) {
     $currencies['VNĐ'] = __( 'Vietnam Dong', 'woocommerce' );
     return $currencies;
}
add_filter('woocommerce_currency_symbol', 'add_my_currency_symbol', 10, 2);
function add_my_currency_symbol( $currency_symbol, $currency ) {
     switch( $currency ) {
          case 'VNĐ': $currency_symbol = '$'; break;
     }
     return $currency_symbol;
}

Add ‘Add to Cart’ button

/**
 * Change the add to cart text on single product pages
 */
function woo_custom_cart_button_text() {
        return __('My Button Text', 'woocommerce');
}
add_filter('single_add_to_cart_text', 'woo_custom_cart_button_text');
/**
 * Change the add to cart text on product archives
 */
function woo_archive_custom_cart_button_text() {
        return __( 'My Button Text', 'woocommerce' );
}
add_filter( 'add_to_cart_text', 'woo_archive_custom_cart_button_text' );

Automatically transfer to the check-out page for payment after adding products into cart

/**
 * Redirect subscription add to cart to checkout page
 *
 * @param none
 */
function add_to_cart_checkout_redirect() {
        wp_safe_redirect( get_permalink( get_option( 'woocommerce_checkout_page_id' ) ) );
        die();
}
add_action( 'woocommerce_add_to_cart',  'add_to_cart_checkout_redirect', 11 );

Send an email to customers when they use coupon for payment

/**
 * WooCommerce Extra Feature
 * --------------------------
 *
 * Send an email each time an order with coupon(s) is completed
 * The email contains coupon(s) used during checkout process
 *
 */
function woo_email_order_coupons( $order_id ) {
        $order = new WC_Order( $order_id );
        if( $order->get_used_coupons() ) {
          $to = 'youremail@yourcompany.com';
                $subject = 'New Order Completed';
                $headers = 'From: My Name ' . "\r\n";
                $message = 'A new order has been completed.\n';
                $message .= 'Order ID: '.$order_id.'\n';
                $message .= 'Coupons used:\n';
                foreach( $order->get_used_coupons() as $coupon) {
                        $message .= $coupon.'\n';
                }
               @wp_mail( $to, $subject, $message, $headers );
        }
}
add_action( 'woocommerce_thankyou', 'woo_email_order_coupons' );

Change the number of involved products

/**
 * WooCommerce Extra Feature
 * --------------------------
 *
 * Change number of related products on product page
 * Set your own value for 'posts_per_page'
 *
 */
function woo_related_products_limit() {
  global $product;
        $args = array(
                'post_type'                     => 'product',
                'no_found_rows'                 => 1,
                'posts_per_page'                => 6,
                'ignore_sticky_posts'   => 1,
                'orderby'               => $orderby,
                'post__in'              => $related,
                'post__not_in'          => array($product->id)
        );
        return $args;
}
add_filter( 'woocommerce_related_products_args', 'woo_related_products_limit' );

Not allow to display products in a certain category to the page ‘Shop’: Replace shoes with the slug of the category you want to remove. More than one can be managed, for example:  array( ‘shoes’, ‘computer’ ).

/**
 * Remove products from shop page by category
 *
 */
function woo_custom_pre_get_posts_query( $q ) {
        if ( ! $q->is_main_query() ) return;
        if ( ! $q->is_post_type_archive() ) return;
        if ( ! is_admin() && is_shop() ) {
                $q->set( 'tax_query', array(array(
                        'taxonomy' => 'product_cat',
                        'field' => 'slug',
                        'terms' => array( 'shoes' ), // Don't display products in the shoes category on the shop page
                        'operator' => 'NOT IN'
                )));
        }
        remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
add_action( 'pre_get_posts', 'woo_custom_pre_get_posts_query' );

Close tabs (Review, Descriptions) in Product area

/**
 * Remove product tabs
 *
 */
function woo_remove_product_tab($tabs) {
    unset( $tabs['description'] );                      // Remove the description tab
    unset( $tabs['reviews'] );                                  // Remove the reviews tab
    unset( $tabs['additional_information'] );   // Remove the additional information tab
        return $tabs;
}
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tab', 98);

Replace ‘Free’ with another word

/**
 * WooCommerce Extra Feature
 * --------------------------
 *
 * Replace "Free!" by a custom string
 *
 */
function woo_my_custom_free_message() {
        return "Ask for the price";
}
add_filter('woocommerce_free_price_html', 'woo_my_custom_free_message');

Hide other modes of transport when the free method is activated

// Hide ALL shipping options when free shipping is available
add_filter( 'woocommerce_available_shipping_methods', 'hide_all_shipping_when_free_is_available' , 10, 1 );
/**
* Hide ALL Shipping option when free shipping is available
*
* @param array $available_methods
*/
function hide_all_shipping_when_free_is_available( $available_methods ) {
        if( isset( $available_methods['free_shipping'] ) ) :
                // Get Free Shipping array into a new array
                $freeshipping = array();
                $freeshipping = $available_methods['free_shipping'];
                // Empty the $available_methods array
                unset( $available_methods );
                // Add Free Shipping back into $avaialble_methods
                $available_methods = array();
                $available_methods[] = $freeshipping;
        endif;
        return $available_methods;
}

Modify the notification after adding items to cart

/**
 * Custom Add To Cart Messages
 * Add this to your theme functions.php file
 **/
add_filter( 'woocommerce_add_to_cart_message', 'custom_add_to_cart_message' );
function custom_add_to_cart_message() {
        global $woocommerce;
        // Output success messages
        if (get_option('woocommerce_cart_redirect_after_add')=='yes') :
                $return_to      = get_permalink(woocommerce_get_page_id('shop'));
                $message        = sprintf('<a href="%s" class="button">%s</a> %s', $return_to, __('Continue Shopping &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
        else :
                $message        = sprintf('<a href="%s" class="button">%s</a> %s', get_permalink(woocommerce_get_page_id('cart')), __('View Cart &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
        endif;
                return $message;
}

Automatically add the name of province/city/state

/**
 * Code goes in functions.php or a custom plugin. Replace XX with the country code your changing.
 */
add_filter( 'woocommerce_states', 'custom_woocommerce_states' );
function custom_woocommerce_states( $states ) {
  $states['XX'] = array(
    'XX1' => 'State 1',
    'XX2' => 'State 2'
  );
  return $states;
}

Edit the number of thumbnail in the Product area

add_filter ( 'woocommerce_product_thumbnails_columns', 'xx_thumb_cols' );
 function xx_thumb_cols() {
     return 4; // .last class applied to every 4th thumbnail
 }

Display the avatar for the Category of products in the page Category

add_action( 'woocommerce_archive_description', 'woocommerce_category_image', 2 );
function woocommerce_category_image() {
    if ( is_product_category() ){
            global $wp_query;
            $cat = $wp_query->get_queried_object();
            $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
            $image = wp_get_attachment_url( $thumbnail_id );
            if ( $image ) {
                    echo '<img src="' . $image . '" alt="" />';
                }
        }
}

Edit the link for ‘Add to Cart’ button

add_filter('add_to_cart_redirect', 'custom_add_to_cart_redirect');
function custom_add_to_cart_redirect() {
     /**
      * Replace with the url of your choosing
      * e.g. return 'http://www.yourshop.com/'
      */
     return get_permalink( get_option('woocommerce_checkout_page_id') );
}
Lengthen the field of filling address
add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');
function custom_woocommerce_billing_fields( $fields ) {
     $fields['billing_address_1']['class'] = array( 'form-row-wide' );
     $fields['billing_address_2']['class'] = array( 'form-row-wide' );
     return $fields;
}

Give examples of product displaying loop

<ul class="products">
        <?php
                $args = array(
                        'post_type' => 'product',
                        'posts_per_page' => 12
                        );
                $<a href="http://thachpham.com/wordpress/wordpress-development/tim-hieu-wordpress-query-va-loop.html" title="loop"><strong>loop</strong></a> = new WP_Query( $args );
                if ( $loop->have_posts() ) {
                       while ( $loop->have_posts() ) : $loop->the_post();
                                woocommerce_get_template_part( 'content', 'product' );
                        endwhile;
                } else {
                        echo __( 'No products found' );
                }
                wp_reset_postdata();
        ?>
</ul><!--/.products-->

Edit the number of products displaying on each page

// Display 24 products per page. Goes in functions.php
add_filter( 'loop_shop_per_page', create_function( '$cols', 'return 24;' ), 20 );

Hide the related products

/*
 * wc_remove_related_products
 *
 * Clear the query arguments for related products so none show.
 * Add this code to your theme functions.php file.
 */
function wc_remove_related_products( $args ) {
        return array();
}
add_filter('woocommerce_related_products_args','wc_remove_related_products', 10);

Delete the product-arranging custom menu

remove_action( 'woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30 )

Allow Product image rounded

Add this code into the file style.css

.woocommerce .woocommerce-tabs {border: 1px solid #e6e6e6}

Put the description under the product image

add_action('woocommerce_after_shop_loop_item_title','woocommerce_template_single_excerpt', 5);

Turn off the SKU function

add_filter( 'wc_product_sku_enabled', '__return_false' );

There are many interesting functions but we highly recommend that if you want complex functions, you should use plugins. Have we missed some things? Drop a comment and talk us about them!

 

Related posts