Category: Woocommerce

Search custom taxonomy term by name

// We get a list taxonomies on the search box
function get_tax_by_search($search_text){

$args = array(
    'taxonomy'      => array( 'my_tax' ), // taxonomy name
    'orderby'       => 'id', 
    'order'         => 'ASC',
    'hide_empty'    => true,
    'fields'        => 'all',
    'name__like'    => $search_text
); 

$terms = get_terms( $args );

 $count = count($terms);
 if($count > 0){
     echo "<ul>";
     foreach ($terms as $term) {
       echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";

     }
     echo "</ul>";
 }

}

// sample
get_tax_by_search('Foo');

WooCommerce edit Myaccount page navigation

Add this code in your theme function.php

function wc_limit_account_menu_items(){
 
 $items = array(
 // 'dashboard' => __( 'Dashboard', 'woocommerce' ),
 'orders' => __( 'Orders', 'woocommerce' ),
 // 'downloads' => __( 'Downloads', 'woocommerce' ),
 'edit-address' => __( 'Address', 'woocommerce' ),
 // 'payment-methods' => __( 'Payment Methods', 'woocommerce' ),
 'edit-account' => __( 'Edit Account', 'woocommerce' ),
 // 'customer-logout' => __( 'Logout', 'woocommerce' )
 );
 

 return $items;
}
add_filter( 'woocommerce_account_menu_items', 'wc_limit_account_menu_items' );

WooCommerce checkout template by hooks

/**
 * Add a content block after all notices, such as the login and coupon notices.
 *
 * Reference: https://github.com/woothemes/woocommerce/blob/master/templates/checkout/form-checkout.php
 */
add_action( 'woocommerce_before_checkout_form', 'skyverge_add_checkout_content', 12 );
function skyverge_add_checkout_content() {
 echo 'This content that you can use to tell customers stuff. You could make it a div class="checkout-message" and style it if you wanted.';
}

/**
 * Add a content in a notice instead. Let's add it before other notices with a priority = 9
 *
 * Reference: https://github.com/woothemes/woocommerce/blob/master/templates/checkout/form-checkout.php
 */
add_action( 'woocommerce_before_checkout_form', 'skyverge_add_checkout_success', 9 );
function skyverge_add_checkout_success() {
 wc_print_notice( __( 'A success message with high priority.', 'woocommerce' ), 'success' );
}


/**
 * Add an info notice instead. Let's add it after other notices with priority = 11
 *
 * Reference: https://github.com/woothemes/woocommerce/blob/master/templates/checkout/form-checkout.php
 */
add_action( 'woocommerce_before_checkout_form', 'skyverge_add_checkout_notice', 11 );
function skyverge_add_checkout_notice() {
 wc_print_notice( __( 'A notice message instead.', 'woocommerce' ), 'notice' );
}


/**
 * Add add a notice before the payment form - let's use an eror notice. Could also use content, etc.
 *
 * Reference: https://github.com/woothemes/woocommerce/blob/master/templates/checkout/review-order.php
 */
add_action( 'woocommerce_review_order_before_payment', 'skyverge_before_paying_notice' );
function skyverge_before_paying_notice() {
 wc_print_notice( __( 'An error message.', 'woocommerce' ), 'error' );
}

WooCommerce hide unavailable veriations from dorpdown

If there are greater than 20 variations in the product, it will use ajax to find matches and won’t hide combinations (because doing so would mean loading all variations before display).

Use is code in your functions.php

function custom_wc_ajax_variation_threshold( $qty, $product ) {
	return 10;
}

add_filter( 'woocommerce_ajax_variation_threshold', 'custom_wc_ajax_variation_threshold', 10, 2 );

 

Change the return value as per your number of combination.

Hide other shipping methods when FREE SHIPPING is available

/**
 * woocommerce_package_rates is a 2.1+ hook
 */
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );
 
/**
 * Hide shipping rates when free shipping is available
 *
 * @param array $rates Array of rates found for the package
 * @param array $package The package array/object being shipped
 * @return array of modified rates
 */
function hide_shipping_when_free_is_available( $rates, $package ) {
 	
 	// Only modify rates if free_shipping is present
  	if ( isset( $rates['free_shipping'] ) ) {
  	
  		// To unset a single rate/method, do the following. This example unsets flat_rate shipping
  		unset( $rates['flat_rate'] );
  		
  		// To unset all methods except for free_shipping, do the following
  		$free_shipping          = $rates['free_shipping'];
  		$rates                  = array();
  		$rates['free_shipping'] = $free_shipping;
	}
	
	return $rates;
}

Show only free shipping in all states except…

Show only free shipping in all states except exclusion list, hide free shipping if the customer is in one of the states listed:

/**
 * Hide ALL shipping options when free shipping is available and customer is NOT in certain states
 * Hide Free Shipping if customer IS in those states
 *
 * UPDATED FOR WOOCOMMERCE 2.1
 *
 * Change $excluded_states = array( 'AK','HI','GU','PR' ); to include all the states that DO NOT have free shipping
 */
add_filter( 'woocommerce_package_rates', 'hide_all_shipping_when_free_is_available' , 10, 2 );

/**
 * Hide ALL Shipping option when free shipping is available
 *
 * @param array $available_methods
 */
function hide_all_shipping_when_free_is_available( $rates, $package ) {
 
	$excluded_states = array( 'AK','HI','GU','PR' );
	if( isset( $rates['free_shipping'] ) AND !in_array( WC()->customer->shipping_state, $excluded_states ) ) :
		// Get Free Shipping array into a new array
		$freeshipping = array();
		$freeshipping = $rates['free_shipping'];
 
		// Empty the $available_methods array
		unset( $rates );
 
		// Add Free Shipping back into $avaialble_methods
		$rates = array();
		$rates[] = $freeshipping;
 
	endif;
 
	if( isset( $rates['free_shipping'] ) AND in_array( WC()->customer->shipping_state, $excluded_states ) ) {
 
		// remove free shipping option
		unset( $rates['free_shipping'] );
 
	}

	return $rates;
}

Enable Shipping Methods on a per Class / Product Basis

If you want to have more flexibility, we recommend you to use this free plugin!

Source: http://docs.woothemes.com/document/hide-other-shipping-methods-when-free-shipping-is-available/

WooCommerce: Hide ‘Coupon form’ on checkout page

This will hide ‘Coupon form’ on checkout page, if any coupon is already applied from cart. Put this code on your function.php.

add_filter( 'woocommerce_coupons_enabled', 'woocommerce_coupons_enabled_checkout' );

function woocommerce_coupons_enabled_checkout( $coupons_enabled ) {
    global $woocommerce;
    if ( ! empty( $woocommerce->cart->applied_coupons ) ) {
        return false;
    }
    return $coupons_enabled;
}

WooCommerce: Restrict payment options based on product

A simple filter to disable a user-specified payment gateway when a product with a user-specified category is added to the shopping cart. Add it to your theme’s functions.php

/*
 * A simple filter to disable a user-specified payment gateway when a product with a user-specified category is added to the shopping cart
 *  - Note:  If multiple products are added and only one has a matching category, it will remove the payment gateway
 * Requires:
 *    payment_NAME : One of the five hardcoded Woocommerce standard types of payment gateways - paypal, cod, bacs, cheque or mijireh_checkout
 *    category_ID :   The ID of the category for which the gateway above will be removed.  Get the ID by clicking on the category under Products -> Categories and reading the "tag_ID" in the address bar
 *                             i.e. http://ubuntu.humble.lan/wp-admin/edit-tags.php?action=edit&taxonomy=product_cat&tag_ID=20&post_type=product <-- the tag_ID is 20
 * Coded by sean _ at _ techonfoot.com
 * Thanks to boxoft - http://stackoverflow.com/questions/15303031/woocommerce-get-category-for-product-page
 * Usual free code disclaimer - use at your own risk
 * This code was tested against Woocommerce 2.1.12  and WordPress 3.9.1 
 */
function filter_gateways($gateways){

$payment_NAME = 'dibs'; // <--------------- change this
$category_ID = '15';  // <----------- and this

 global $woocommerce;

 foreach ($woocommerce->cart->cart_contents as $key => $values ) {
    // Get the terms, i.e. category list using the ID of the product
    $terms = get_the_terms( $values['product_id'], 'product_cat' );
    // Because a product can have multiple categories, we need to iterate through the list of the products category for a match
    foreach ($terms as $term) {
        // 20 is the ID of the category for which we want to remove the payment gateway
        if($term->term_id == $category_ID){
               unset($gateways[$payment_NAME]);
                   // If you want to remove another payment gateway, add it here i.e. unset($gateways['cod']);
                    break;
          }
        break;
    }

   }
    return $gateways;

}

add_filter('woocommerce_available_payment_gateways','filter_gateways');

 

 

WooCommerce: Display Price For Variable Product With Same Variations Prices

// Display Price For Variable Product With Same Variations Prices
add_filter('woocommerce_available_variation', function ($value, $object = null, $variation = null) {
    if ($value['price_html'] == '') {
        $value['price_html'] = '<span class="price">' . $variation->get_price_html() . '</span>';
    }
    return $value;
}, 10, 3);

WooCommerce: Product setup fee for 1st purchase

If  you want to add additional set-up fee for 1st time purchase this code will do that. If any customer want to buy any product for 1st time he/she need to pay additional set-up fee for that product. There will be not additional charge for repeat purchase.

 

 

 

Add this code in your function.php

/**
 * Uses the WooCommerce fees API
 *
 * Add to theme functions.php
 */
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
  global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $current_user = wp_get_current_user();
        
        if ( 0 == $current_user->ID ) { // User not login
        
    $surcharge  = 10;
    
        $car_item = $woocommerce->cart->get_cart_item_quantities( ); // get wooCommerce current cart items
    $product_ids = array_keys($car_item); // cart item product ids
    
    foreach($product_ids as $product_id)
     {
     $term_list = wp_get_post_terms($product_id,'product_cat',array('fields'=>'ids')); // Check product category
     $cat_id = (int)$term_list[0]; // product category id
     $product_name = get_the_title($product_id); // Product name
     
     if($cat_id == 18 || $cat_id == 21 || $cat_id == 22) // Matching product category
      {
        
        $woocommerce->cart->add_fee( 'Setup fee for '.$product_name, $surcharge, true, 'standard' );
        
      }
     
        
     }
    
    } else {
    // Logged in.
     $customer_id = $current_user->ID;
     $car_item = $woocommerce->cart->get_cart_item_quantities( );
     $product_ids = array_keys($car_item);
     
     /*
     * Get all oder ids of current user
     *
     */
     $args = array(
        'numberposts'     => -1,
        'meta_key'        => '_customer_user',
        'meta_value'      => $customer_id ,
        'post_type'       => 'shop_order',
        'post_status'     => 'publish',
        /*'tax_query'=>array(
                array(
                    'taxonomy'  =>'shop_order_status',
                    'field'     => 'slug',
                    'terms'     =>$status
                    )
        ) */ 
    );
    
    $posts=get_posts($args);
    //get the post ids as order ids
    $orders=wp_list_pluck( $posts, 'ID' );
    
    /*
    *
    * Get all products id purchased by current user
    */
    
    foreach($orders as $order)
      {
    $order = new WC_Order( $order );
        $items = $order->get_items();
    
      foreach ( $items as $item ) {
        
        $p_id[] = $item['product_id'];
        
        }
    
      }
      
     $p_id = array_unique($p_id); 
    foreach($product_ids as $product_id)
     {
     $term_list = wp_get_post_terms($product_id,'product_cat',array('fields'=>'ids'));
     $cat_id = (int)$term_list[0];
     $product_name = get_the_title($product_id);
     
     if($cat_id == 18 || $cat_id == 21 || $cat_id == 22)
      {
       
        if (!in_array($product_id, $p_id )) {
        $surcharge = 10;
         $woocommerce->cart->add_fee( 'Setup fee for '.$product_name, $surcharge, true, 'standard' );
        }    
       
        
      }
     
        
     }
     
     
    
    
}
    

}

WooCommerce: Add a surcharge to cart and checkout – uses fees API

Add a basic surcharge to all transactions

/**
 * Add a 1% surcharge to your cart / checkout
 * change the $percentage to set the surcharge to a value to suit
 * Uses the WooCommerce fees API
 *
 * Add to theme functions.php
 */
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
  global $woocommerce;

	if ( is_admin() && ! defined( 'DOING_AJAX' ) )
		return;

	$percentage = 0.01;
	$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;	
	$woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, 'standard' );

}


Source: http://docs.woothemes.com/document/add-a-surcharge-to-cart-and-checkout-uses-fees-api/

Add a surcharge based on the delivery country

/**
 * Add a 1% surcharge to your cart / checkout based on delivery country
 * Taxes, shipping costs and order subtotal are all included in the surcharge amount
 *
 * Change $percentage to set the surcharge to a value to suit
 *
 * Add countries to array('US'); to include more countries to surcharge
 * http://en.wikipedia.org/wiki/ISO_3166-1#Current_codes for available alpha-2 country codes 
 *
 * Change in_array to !in_array to EXCLUDE the $countries array from surcharges
 *
 * Uses the WooCommerce fees API
 * Add to theme functions.php
 */
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
  global $woocommerce;
 
	if ( is_admin() && ! defined( 'DOING_AJAX' ) )
		return;

 	$county 	= array('US');
	$percentage 	= 0.01;

	if ( in_array( $woocommerce->customer->get_shipping_country(), $county ) ) :
		$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
		$woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, 'standard' );
	endif;
 
}