wordpress woocommerce customisation code snippets

freemium solutions

I have a lot of mixed feelings about freemium solutions. Yep, they are for free and give you some basic functionality for free. But usually the thing that you need… is paid section. I have nothing against paid solutions and I use them. But sometimes the price tag of this only feature is quite high! So…. why not code them?

I know. Coding sounds scary to some. So I’ve decided to share some solutions I’ve discovered during my adventures with WooCommerce customisations for free. I’ll try to do this in the most humane way possible ;P

how to use code in wordpress

There are 2 main ways to embed the code in WordPress.

1. The harder way – directly editing functions.php

The easier way below automates adding, enabling, disabling and deleting the code in functions.php so why waste time?

2. The easier way – through a plugin

There are plenty of them, but I use Code Snippet for all of my needs. If you know how to install the plugin, please skip to this section. The plugin is good to go in default settings out of the box for basics. And if you need more… GO PRO.

1. Go to Plugins:

2. Go to Add new:

3. Enter keywords: “code snippet” and then click “Install Now” on the plugin widget.

4. Click “Activate” on the plugin widget.

5. You should see the “Snippets” on the left hand menu:

The plugin is installed and ready to use. When you click it, you should see the below window. Feel free to look around. It’s pretty self explanatory. Clicking the title if the code, opens a window with the code.

Adding the new code snippet is also pretty straight forward. Just click “Add new”.

Now. Let’s move to coding 🙂

woocommerce automatic change of order status to completed

One of my ecommerce projects was selling access to content. the client wanted the order to be completed automatically after the payment was authorised.

Steps in the Code Snippet: Enter title -> copy paste the code -> you may add description -> Save changes and activate

Viola!

add_action( 'woocommerce_payment_complete', 'ms_autocomplete_paid_orders' );
function ms_autocomplete_paid_orders( $order_id ) { 
    if ( ! $order_id ) {
        return;
    }
 
    $order = wc_get_order( $order_id );
    $order->update_status( 'completed' );

}

replace woocommerce sale print

You cant do anything with the print if you don’t like it without buying plugins. You may write some code however. In this example we wanted it to be “%” only. Feel free to customise as you need.

Steps in the Code Snippet: Enter title -> copy paste the code -> you may add description -> Save changes and activate

Viola!

If you need to change styles, please add the CSS part to your themes styling file. In this example we changed the font colour to white (#ffffff).

add_filter('woocommerce_sale_flash', 'ms_change_sale_text');
function ms_change_sale_text() {
return '<span class="onsale"><b>%</b></span>';
}


Custom CSS
/* font color of WooCommerce sale bage!
.woocommerce span.onsale {
color: #ffffff !important;
}
*/

manage woocommerce checkout fields

It’s pretty straightforward. There are plenty of checkout fields. You may not need them all. And why to pay for a plugin, when you can use a simple code?

I have listed all regular woocommerce fields. You may have additional if you are using dedicated customisations. Rules are simple in this code:

Steps in the Code Snippet: Enter title -> copy paste the code -> customise unset attributes -> you may add description -> Save changes and activate

  • “// unset” – field is visible and may be required
  • “unset” – field is not visible and not required
function ms_remove_checkout_fields( $fields ) {

// Billing fields
//    unset( $fields['billing']['billing_company'] );
//    unset( $fields['billing']['billing_email'] );
    unset( $fields['billing']['billing_phone'] );
//    unset( $fields['billing']['billing_state'] );
//    unset( $fields['billing']['billing_first_name'] );
//    unset( $fields['billing']['billing_last_name'] );
//    unset( $fields['billing']['billing_address_1'] );
    unset( $fields['billing']['billing_address_2'] );
//    unset( $fields['billing']['billing_city'] );
//    unset( $fields['billing']['billing_postcode'] );
//    unset( $fields['billing']['billing_country']);
	
// Shipping fields
/**
    unset( $fields['shipping']['shipping_company'] );
    unset( $fields['shipping']['shipping_phone'] );
    unset( $fields['shipping']['shipping_state'] );
    unset( $fields['shipping']['shipping_first_name'] );
    unset( $fields['shipping']['shipping_last_name'] );
    unset( $fields['shipping']['shipping_address_1'] );
    unset( $fields['shipping']['shipping_address_2'] );
    unset( $fields['shipping']['shipping_city'] );
    unset( $fields['shipping']['shipping_postcode'] );
	unset( $fields['shipping']['shipping_country']);
**/
	
// Order fields
	unset( $fields['order']['order_comments'] );
	

    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'ms_remove_checkout_fields' );
add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );

Viola!

manage woocommerce my account elements

woocommerce “My Account” has several areas visible by default. you may want to hide them as they are not needed. woocommerce calls them “endpoints”

I have listed all regular woocommerce tabs. You may have additional if you are using dedicated customisations. Rules are simple in this code:

  • “// unset” – area is visible and accessible
  • “unset” – area is not visible and not accessible

Steps in the Code Snippet: Enter title -> copy paste the code -> customise unset attributes -> you may add description -> Save changes and activate

Viola!

function ms_remove_my_account_links( $menu_links ){
    
    //unset( $menu_links['dashboard'] );        // Remove Dashboard
    // unset( $menu_links['edit-address'] );     // Addresses
    //unset( $menu_links['payment-methods'] );  // Remove Payment Methods
    //unset( $menu_links['orders'] );           // Remove Orders
    unset( $menu_links['downloads'] );        // Disable Downloads
    //unset( $menu_links['edit-account'] );     // Remove Account details tab
    //unset( $menu_links['customer-logout'] );  // Remove Logout link
    
    return $menu_links;
}
add_filter ( 'woocommerce_account_menu_items', 'ms_remove_my_account_links' );

manage woocommerce product elements

woocommerce default product presentation may also be customised.

I have listed all regular woocommerce tabs. You may have additional if you are using dedicated customisations. Rules are again simple in this code:

  • “// unset” – area is visible and accessible
  • “unset” – area is not visible and not accessible
  • each row describes what is shown or removed

Steps in the Code Snippet: Enter title -> copy paste the code -> customise unset attributes -> you may add description -> Save changes and activate

Viola!

function ms_remove_product_tabs($tabs) {
	unset($tabs['description']); // Remove Description
// unset($tabs['additional_information']); // Remove Additional Information
// unset($tabs['reviews']); // Remove Reviews
return $tabs; } add_filter( 'woocommerce_product_tabs', 'ms_remove_product_tabs', 98 );

manage woocommerce check-out terms and conditions

This code is a big longer. The EU regulations forced one of my clients to force accept my clients to accept terms and conditions, before proceeding to payment. The below code adds two checkboxes with links to the source, and validates if boxes are checked before allowing to proceed to payment.

Please pay attention to the following elements, as they need to be customised to your requirements:

  • /regulations/ – is a link to shops terms and conditions web site
  • ‘label’ => sprintf( __( ‘I have read and accept <a href=”%s” target=”_blank”>the terms and conditions</a>’, ‘woocommerce’ ), esc_url( $terms_and_conditions_link ) ),
  • ‘label’ => __( ‘I agree for the digital content to be delivered to me immediately before the applicable resignation term. I am aware that I loose the right to withdraw from the contract.’, ‘woocommerce’ ),
  • wc_add_notice( __( ‘In order to proceed, please read and accept the terms and conditions.’, ‘woocommerce’ ), ‘error’ ); }
  • wc_add_notice( __( ‘To make a purchase, you must agree to the delivery of the digital content included in the order before the deadline for withdrawal from the contract expires’, ‘woocommerce’ ), ‘error’ );
  • you may as well limit yourself to one of these, or merge them

Steps in the Code Snippet: Enter title -> copy paste the code -> customise unset attributes -> you may add description -> Save changes and activate

Viola!

add_action( 'woocommerce_checkout_after_terms_and_conditions', 'add_checkout_checkboxes', 10 );

function add_checkout_checkboxes() {
    $terms_and_conditions_link = '/regulation/';
    woocommerce_form_field( 'terms_and_conditions', array(
        'type'          => 'checkbox',
        'class'         => array('form-row terms'),
        'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
        'input_class'   => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
        'required'      => true,
        'label'         => sprintf( __( 'I have read and accept <a href="%s" target="_blank">the terms and conditions</a>', 'woocommerce' ), esc_url( $terms_and_conditions_link ) ),
        'default'       => false,
    ),  WC()->checkout->get_value( 'terms_and_conditions' ) );

    woocommerce_form_field( 'add_digital_checkbox', array(
        'type'          => 'checkbox',
        'class'         => array('form-row terms'),
        'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
        'input_class'   => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
        'required'      => true,
        'label'         => __( 'I agree for the digital content to be delivered to me immediately before the applicable resignation term. I am aware that I loose the right to withdraw from the contract.', 'woocommerce' ),
        'default'       => false,
    ),  WC()->checkout->get_value( 'add_digital_checkbox' ) );
}


// Validate required fields before checkout submission
add_action( 'woocommerce_checkout_process', 'validate_terms_field_checkout' );
function validate_terms_field_checkout() {
    $terms = isset( $_POST['terms_and_conditions'] );
    if ( ! $terms ) {
        wc_add_notice( __( 'In order to proceed, please read and accept the terms and conditions.', 'woocommerce' ), 'error' );
    }
}

// Validate required fields before checkout submission
add_action( 'woocommerce_checkout_process', 'validate_digital_field_checkout' );
function validate_digital_field_checkout() {
    $digital = isset( $_POST['add_digital_checkbox'] );
    if ( ! $digital ) {
        wc_add_notice( __( 'To make a purchase, you must agree to the delivery of the digital content included in the order before the deadline for withdrawal from the contract expires', 'woocommerce' ), 'error' );
    }
}

manage woocommerce coming soon badge

This code adds a coming soon badge to product on backorder status in the shop. We use it to display products which are about to be available shortly.

The second part of this code does not allow clients to open product details when a product has the coming soon badge.

Steps in the Code Snippet: Enter title -> copy paste the code -> you may add description -> Save changes and activate

Custom CSS section needs to be put in your theme’s custom CSS styling.

add_action( 'woocommerce_before_shop_loop_item_title', 'add_coming_soon_badge_to_shop_page', 10 );

function add_coming_soon_badge_to_shop_page() {
    global $product;
    if ( $product->is_on_backorder() ) {
        echo '<span class="coming-soon-badge">' . __( 'W przygotowaniu', 'woocommerce' ) . '</span>';
    }
}

add_filter( 'woocommerce_loop_product_link', 'disable_link_to_product_details_for_coming_soon_products', 10, 2 );

function disable_link_to_product_details_for_coming_soon_products( $link, $product ) {
    if ( $product->is_on_backorder() ) {
        return '';
    }
    return $link;
}

Custom CSS
.coming-soon-badge {
    position: absolute;
    top: 0;
    left: 0;
    display: inline-block;
    padding: 5px 10px;
    font-size: 14px;
    font-weight: bold;
    background-color: #ff5151;
    color: #fff;
    border-radius: 3px;
    z-index: 999;
}

.product-image-wrapper {
    position: relative;
}

.product-image-wrapper .coming-soon-badge {
    position: absolute;
    top: 0;
    left: 0;
}

Viola!

limit search function to woocommerce products

In one of the projects we wanted to limit WordPress search function to go through products only. The code does exactly this.

Steps in the Code Snippet: Enter title -> copy paste the code -> you may add description -> Save changes and activate

Viola!

function ms_search_filter_pages($query) {
if ($query->is_search) {
$query->set('post_type', 'product');
$query->set( 'wc_query', 'product_query' );
}
return $query;
}
 
add_filter('pre_get_posts','ms_search_filter_pages');

add “Tax ID” to woocommerce billing information

If your eccommerce platform is issuing VAT invoices to the EU firms or corporate clients, they have to contain the EU TAX ID (VAT ID). The code below adds this field to the billing information. The second part of the code makes the Tax ID field mandatory for companies.

Elements requiring your attention and customisation:

  • ‘label’ => __(‘Tax ID’, ‘woocommerce’),
  • c_add_notice(__(‘Enter the company’s Tax ID, e.g. VAT ID.’, ‘woocommerce’), ‘error’);

Steps in the Code Snippet: Enter title -> copy paste the code -> customise attributes -> you may add description -> Save changes and activate

Viola!

// Add custom billing field 'Tax ID'
add_filter('woocommerce_billing_fields', 'add_custom_billing_tax_no_field', 10, 1);
function add_custom_billing_tax_no_field($fields) {
    $fields['billing_tax_no'] = array(
        'label'       => __('Tax ID', 'woocommerce'),
        'placeholder' => __('', 'woocommerce'),
        'required'    => false,
        'clear'       => true,
        'priority'    => 30,
    );

    return $fields;
}

// Make 'Tax ID' field mandatory if 'Company' field is not empty
add_action('woocommerce_checkout_process', 'validate_billing_tax_no_field');
function validate_billing_tax_no_field() {
    if (isset($_POST['billing_company']) && !empty($_POST['billing_company'])) {
        $tax_id = isset($_POST['billing_tax_no']) ? sanitize_text_field($_POST['billing_tax_no']) : '';

        if (empty($tax_id)) {
            wc_add_notice(__('Enter the company's Tax ID, e.g. VAT ID.', 'woocommerce'), 'error');
        }
    }
}

Marcin avatar

Leave a Reply

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