Category: Woocommerce

  • Clearing the Cart After Placing an Order on WooCommerce: A PHP Code Snippet Guide

    In this guide, we’ll show you how to clear the cart automatically after placing an order on WooCommerce using a PHP code snippet. By implementing this code snippet in the appropriate location, you can ensure a clean slate for your customers, promoting an organized and hassle-free shopping experience.

    function clear_cart_on_order_creation( $order_id ) {
        if ( ! $order_id ) {
            return;
        }
    
        WC()->cart->empty_cart();
    }
    add_action( 'woocommerce_new_order', 'clear_cart_on_order_creation', 10, 1 );

    You can add the PHP Snippet on Theme’s functions.php file or you can create a plugin to clear the cart when order is created.

  • Preventing Empty Orders in WooCommerce: A Quick Guide

    Empty orders in WooCommerce can be frustrating for both customers and businesses. By implementing simple PHP snippets, you can ensure that orders are not placed without any products. This quick guide will walk you through the steps to validate carts and delete empty orders, improving the overall user experience and order management efficiency.

    1. Disabling Checkout for Empty Carts:

    To prevent orders without products, use this PHP snippet to disable the checkout button if the cart is empty:

    add_filter('woocommerce_is_purchasable', 'disable_checkout_on_empty_cart', 10, 2);
    function disable_checkout_on_empty_cart($is_purchasable, $product) {
        if (WC()->cart->is_empty()) {
            $is_purchasable = false;
        }
        return $is_purchasable;
    }

    2. Deleting Orders without Products:

    If an order is placed without any products, it’s best to delete it automatically. Use this PHP snippet to delete orders without products:

    add_action('woocommerce_new_order', 'delete_empty_orders', 10, 1);
    function delete_empty_orders($order_id) {
        $order = wc_get_order($order_id);
        if (count($order->get_items()) === 0) {
            $order->delete(true);
        }
    }

    By implementing these PHP snippets, you can ensure that empty orders are prevented and efficiently managed in WooCommerce. Disabling checkout for empty carts improves the user experience by prompting customers to add products before proceeding. Deleting orders without products keeps your order management streamlined and clutter-free.

    Remember, validating carts and deleting empty orders are crucial steps to maintain a seamless customer journey in WooCommerce.

  • How to Add a New Tab on the Single Product Page in WooCommerce

    Adding a new tab with product meta on the single product page in WooCommerce can be a great way to provide additional information about your products to your customers. In this post, we’ll walk you through the steps to add a new tab with product meta on the single product page in WooCommerce.

    Step 1: Open functions.php To add a new tab with product meta on the single product page in WooCommerce, you’ll need to open your theme’s functions.php file. This file is located in your theme’s directory and contains all of the functions that your theme uses.

    Step 2: Add the Code Once you’ve opened your functions.php file, you can add the following code to add a new tab with product meta on the single product page:

    function add_new_product_tab( $tabs ) {
        $tabs['new_tab'] = array(
            'title'     => __( 'New Tab', 'woocommerce' ),
            'priority'  => 50,
            'callback'  => 'new_tab_content'
        );
        return $tabs;
    }
    add_filter( 'woocommerce_product_tabs', 'add_new_product_tab' );
    
    function new_tab_content() {
        global $product;
        echo '<h2>New Tab Content</h2>';
        echo '<p>Product SKU: ' . $product->get_sku() . '</p>';
        echo '<p>Product Weight: ' . $product->get_weight() . '</p>';
        echo '<p>Product Dimensions: ' . $product->get_dimensions() . '</p>';
    }
    

    This code adds a new tab called “New Tab” with product meta information such as SKU, weight, and dimensions. You can customize this code to fit your specific needs.

    Step 3: Save and Test Once you’ve added the code to your functions.php file, save the file and test your new tab. You should now see a new tab on the single product page in WooCommerce with the product meta information you specified.

    We hope you found this post helpful. If you have any questions or comments, please feel free to leave them below!

  • How to Retrieve the Quantity of a Product from the WooCommerce Cart

    Introduction:

    One common functionality that store owners often need is to retrieve the quantity of a particular product in a customer’s cart. In this post, we’ll walk you through the steps to achieve this using WooCommerce hooks and functions. Let’s dive in!

    Step 1: Identify the product to retrieve its quantity

    To begin with, you need to know the product ID or product SKU for the item whose quantity you want to retrieve. You can find this information in the WooCommerce Products section in your WordPress dashboard. Once you have the product ID or SKU, you can proceed to the next step.

    Step 2: Create a custom function to get the product quantity

    Now, you need to create a custom function that will retrieve the quantity of the specified product from the cart. You can add this function to your theme’s functions.php file or in a custom plugin file. Here’s a sample code snippet:

    function get_product_quantity_from_cart( $product_id ) {
      $quantity = 0;
    
      // Check if the cart is not empty
      if ( ! WC()->cart->is_empty() ) {
        // Loop through the cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
          // Check if the current cart item matches the specified product ID
          if ( $cart_item['product_id'] == $product_id ) {
            // Update the quantity
            $quantity = $cart_item['quantity'];
            break;
          }
        }
      }
    
      return $quantity;
    }

    This function checks if the WooCommerce cart is not empty and then loops through the cart items. If the product ID matches the specified product, it retrieves the quantity and breaks the loop.

    Step 3: Use the custom function in your theme or plugin

    Now that you have the custom function, you can use it in your theme or plugin to display the quantity of the specified product in the cart. For example, you can call the function like this:

    $product_id = 123; // Replace with your product ID
    $quantity = get_product_quantity_from_cart( $product_id );
    echo 'The quantity of product ID ' . $product_id . ' in the cart is: ' . $quantity;

    This will output the quantity of the specified product in the cart.

    Conclusion:

    Retrieving the quantity of a product in the WooCommerce cart is a straightforward process. By creating a custom function and using it in your theme or plugin, you can efficiently access this information and use it for various purposes like displaying stock availability, offering dynamic discounts, or managing shipping options. With a bit of creativity, you can customize your WooCommerce store to better serve your customers and improve their shopping experience.

  • Modify Shipping Methods Programatically in Woocommerce

    Modify Shipping Methods Programatically in Woocommerce is normal for any E-Commerce website build on WordPress using Woocomemrce. A lot of people gets confused when it comes to use woocommerce_package_rates filter on woocommerce to change shipping methods conditionally. I was one of them too. But woocommerce_package_rates do all stuff required to modify/remove shipping methods programatically.

    Paste this code in theme_dir/functions.php

    /**
      * Free Shipping if total is more then 200 USD excluding Coupons, Taxes or any other fees.
      *
      **/
    add_filter( 'woocommerce_package_rates',  'modify_shipping_rate', 15, 2 );
    function modify_shipping_rate( $available_shipping_methods, $package ){
        global $woocmmerce;
    
        // Cart Subtotal
        $total_coast = WC()->cart->get_cart_contents_total();
        if( $total_coast >= 200 ){
            // "free_shipping:1" is the Shipping Method ID
            
            if(isset($available_shipping_methods['free_shipping:1'])) {
                // Change Cost of Shipping Method
                $available_shipping_methods['free_shipping:1']->cost = 0;
    
                // Remove Shipping Method
                unset($available_shipping_methods['local_pickup:1']);
            }
        }
        return $available_shipping_methods;
    }

    Remember to clear cart and add products again, after adding woocommerce_package_rates filter.

    You will have to change Shipping Method IDs according to your conditions. In this code it is free_shipping:1.

    Find Shipping Methods ID

    1. Inspect Element on the Shipping Method.
    2. flat_rate:1 will be the Shipping Method ID as shown in the screenshot.

    Modify Shipping Methods Programatically in Woocommerce is a simple method to complete your needs easily with less load

  • Custom Shipping Methods Woocommerce

    Custom Shipping Method is a smart move if you want to show shipping methods according to your needs using some parameters/fields in woocommerce.

    To create a Custom Shipping Method, You will have to create a plugin using below code.

    1. Create a folder custom-shipping-method in wp-content/plugins.
    2. Create a file inside custom-shipping-method folder named custom-shipping-method.php and paste the code below.
    <?php
    
    /*
    Plugin Name: Custom Shipping Method
    Plugin URI: #
    description: Custom Shipping Rates and Delivery
    Version: 1.0
    Author: Sanchit Varshney
    Author URI: #
    License: GPL2
    */
    
    
    if ( ! defined( 'ABSPATH' ) ) {
        exit; // Exit if accessed directly
    }
    
    if (
        in_array(
            'woocommerce/woocommerce.php',
            apply_filters('active_plugins', get_option('active_plugins'))
        )
    ) {
        //Add Custom Shipping Method
        add_action( 'woocommerce_shipping_init', 'custom_shipping_method' );
    
        function custom_shipping_method() {
    
            if ( ! class_exists( 'Custom_Shipping_Method' ) ) {
                class Custom_Shipping_Method extends WC_Shipping_Method {
                
                    /**
                    * Constructor for your shipping class
                    *
                    * @access public
                    * @return void
                    */
                    
                    public function __construct() {
                    
                        $this->id                 = 'custom';
                        $this->method_title       = __( 'Custom Shipping', 'custom' );
                        $this->method_description = __( 'Custom Shipping Method', 'custom' );
                        $this->init();
                        $this->enabled = isset( $this->settings['enabled'] ) ? $this->settings['enabled'] : 'yes';
                        $this->title = isset( $this->settings['title'] ) ? $this->settings['title'] : __( 'Custom Shipping', 'custom' );
                        $this->availability = 'including';
    
                        // Country is set to Romania by Default
                        $this->countries = array('RO');
                    }
                    
                    /**
                    * Init your settings
                    *
                    * @access public
                    * @return void
                    */
                    
                    function init() {
                        // Load the settings API
                        $this->init_form_fields();
                        $this->init_settings();
                        // Save settings in admin if you have any defined
                        add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
                    }
                    
                    /**
                    * Define settings field for this shipping
                    * @return void
                    */
                    
                    function init_form_fields() {
                        // We will add our settings here
                        $this->form_fields = array(
                            'enabled' => array(
                                'title' => __( 'Enable', 'shiprocket' ),
                                'type' => 'checkbox',
                                'description' => __( 'Enable this shipping.', 'custom' ),
                                'default' => 'no'
                            ),
                            'bucharest_fan_courier' => array(
                                'title' => __( 'Bucharest (Fan Courier)', 'custom' ),
                                'type' => 'number',
                                'description' => __( 'Bucharest (Fan Courier) delivery charges.', 'custom' ),
                                'default' => 14.99
                            ),
                            'bucharest_beefast' => array(
                                'title' => __( 'Bucharest (Beefast)', 'custom' ),
                                'type' => 'number',
                                'description' => __( 'Bucharest (Beefast) delivery charges.', 'custom' ),
                                'default' => 9.99
                            ),
                            'ilfov_fan_courier' => array(
                                'title' => __( 'Ilfov (Fan Courier)', 'custom' ),
                                'type' => 'number',
                                'description' => __( 'Ilfov (Fan Courier) delivery charges.', 'custom' ),
                                'default' => 14.99
                            ),
                            'gls' => array(
                                'title' => __( 'Rest of Country (GLS)', 'custom' ),
                                'type' => 'number',
                                'description' => __( 'Rest of Country (GLS) delivery charges.', 'custom' ),
                                'default' => 16.99
                            )
                        );
                    }
                    
                    /**
                    * This function is used to calculate the shipping cost. Within this function, we can check for weights, dimensions, and other parameters.
                    *
                    * @access public
                    * @param mixed $package
                     @return void
                    */
                    public function calculate_shipping( $package = array() ) {
    
                        // Get Country
                        $country = $package["destination"]["country"];
    
                        // Get Postcode
                        $postcode = $package["destination"]["postcode"];
    
                        // Get City
                        $city = $package["destination"]["city"];
    
                        // We're going to use only state field to show shipping methods. 
                        // You can use any according to your needs.
    
                        // Selected State from Checkout Fields
                        $state = $package["destination"]["state"];
                        $rates = array();
    
                        // Shipping Methods will be only shown if State is selected.
                        if(!empty($state)) {
    
                            // Creating Rates/Methods according to State Value
                            switch($state) {
                                case 'B':
                                    $rate_1 = array(
                                        'id' => 'bucharest_beefast',
                                        'label' => 'Livrare Rapidă',
                                        'cost' => isset( $this->settings['bucharest_beefast'] ) ? $this->settings['bucharest_beefast'] : 0
                                    );
                                    $rate_2 = array(
                                        'id' => 'bucharest_fan_courier',
                                        'label' => 'Livrare Fan Courier',
                                        'cost' => isset( $this->settings['bucharest_fan_courier'] ) ? $this->settings['bucharest_fan_courier'] : 0
                                    );
                                    array_push($rates, $rate_1);
                                    array_push($rates, $rate_2);
                                    break;
                                case 'IF':
                                    $rate_1 = array(
                                        'id' => 'ilfov_fan_courier',
                                        'label' => 'Livrare Fan Courier',
                                        'cost' => isset( $this->settings['ilfov_fan_courier'] ) ? $this->settings['ilfov_fan_courier'] : 0
                                    );
                                    array_push($rates, $rate_1);
                                    break;
                                default:
                                    $rate_1 = array(
                                        'id' => 'gls',
                                        'label' => 'Livrare GLS',
                                        'cost' => isset( $this->settings['gls'] ) ? $this->settings['gls'] : 0
                                    );
                                    array_push($rates, $rate_1);
                                    break;
                            }
                
                            // Adding Rates/Methods to show on Checkout Screen
                            foreach($rates as $rate) {
                                $this->add_rate( $rate ); 
                            }
                        }
                    }
                }
            }
        }
    
        function add_custom_shipping_method( $methods ) {
            $methods[] = 'Custom_Shipping_Method';
            return $methods;
        }
        add_filter( 'woocommerce_shipping_methods', 'add_custom_shipping_method' );
    }
    • That’s It. Go to Plugin in wp-admin dashboard and Activate the plugin.
    • Find plugin settings in Woocommerce >> Settings >> Shipping >> Custom Shipping.
    • Test Custom Shipping Methods by Adding Products. (Remember to change country code in plugin on line no. 50 or remove it if you’re going to use it for all countries).
    • You can modify the code according to your needs.
    Shipping Method Settings

    Creating Custom Shipping Methods for Woocommerce is super easy. Still, If you are stuck anywhere feel free to comment on the post, I will reply back with the solution ASAP.

  • Litespeed Cache with Woocommerce

    Litespeed Cache is one of the best caching plugin on wordpress but sometimes it makes things worse on wordpress website. On this post we are going to talk about how we can make it work with woocommerce.

    Known Issues

    1. Cart Items Count getting cached.
    2. Add to Cart using Ajax doesn’t work.
    3. Woocommerce Pages getting cached (like My Account, Cart, Checkout and Thank You Page).

    Fix Cart Items Count getting Cached

    • Go to Litespeed Cache (Dashboard) >> Cache
    Litespeed Cache Menu on Dashboard
    • Open Excludes Tab and Scroll down to “Do Not Cache Cookies” Field
    • Write “woocommerce_items_in_cart” in the Field and Clear Cache
    Do Not Cache Cookies Field

    Fix Add to Cart using Ajax

  • Go to Litespeed Cache (Dashboard) >> Cache
    • Disable Cache Rest API
    Rest API Option

    Fix Woocommerce Pages

  • Go to Litespeed Cache (Dashboard) >> Cache
  • Open Excludes Tab and Scroll down to “Do Not Cache URIs” Field
  • and add:

    /cart
    /checkout
    /my-account/$
    /order-received/$
    /order-pay/$
    Do Not Cache URIs Field

    These three steps will make your woocommerce fast and stable using Litespeed Cache with no more cache issues.

  • Disable User Password Change Email/Notification on WordPress

    Wondering, How to disable user password change emails/notifications. Here is your answer.

    Disable Password Change Email to Admin

    Note: Create a Plugin or Add this code inside a custom plugin to make this code work.

    /**
     * Disable Admin Notification of User Password Change
     *
     * @see pluggable.php
     */
    if ( ! function_exists( 'wp_password_change_notification' ) ) {
        function wp_password_change_notification( $user ) {
            return;
        }
    }

    Suppressing this email notification has to handled with a plugin because pluggable.php is loaded earlier than a theme’s functions.php file.

    Disable Password Change Email to Users

    /**
     * Disable User Notification of User Password Change
     */
    add_filter( 'send_password_change_email', '__return_false' );

    Add above line of code in functions.php of your theme to disable user password change emails to users itself.

  • How To Use AJAX In WordPress

    Want to do something without even reloading the page on wordpress ?
    Use WP Ajax.

    Using WP Ajax, You can do stuff asynchronously like Add to Cart, Refresh Fragments, Change Quantity of Products, Load more posts and many more.

    How to create Ajax Calls in WordPress ?

    1. Create Ajax Actions on WordPress.

    Example: Woocoommerce Add to Cart with Quantity using Ajax

    Add this inside your theme’s functions.php file.

    <?php
    // Add AJAX for logged in users.
    add_action("wp_ajax_cmw_add_to_cart", "cmw_add_to_cart");
    
    // Add AJAX for not logged in users.
    add_action("wp_ajax_nopriv_cmw_add_to_cart", "cmw_add_to_cart");
    
    function cmw_add_to_cart() {
    
       // Verify Nonce
       if ( !wp_verify_nonce( $_REQUEST['nonce'], "cmw_add_to_cart_nonce")) {
          die("404 Access Denied");
       }
    
       if(isset($_REQUEST['product_id']) && isset($_REQUEST['quantity'])) {
          $product_id = $_REQUEST['product_id'];
          $quantity = $_REQUEST['quantity'];
          WC()->cart->add_to_cart( $product_id, $quantity);
          echo json_encode(array("added"=>true));
       }
       die();
    }

    2. Create jQuery to Trigger Ajax

    Add this inside your theme’s functions.php file.

    add_action('wp_enqueue_scripts', 'cmw_enqueue_js');
    function cmw_enqueue_js() {
    
        // Register Custom JS File (We will put Ajax Code inside this file);
        // Use get_template_directory_uri for Theme.
        // Use get_stylesheet_directory_uri for Child Theme.
        wp_register_script( "cmw_script", get_template_directory_uri().'/css/cmw_script.js', array('jquery') );
       
        wp_localize_script( 'cmw_script', 'cmw', array( "ajaxurl" => admin_url( 'admin-ajax.php' ), "nonce" => wp_create_nonce("cmw_add_to_cart_nonce")));        
       
       
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'cmw_script' );
    }

    Add this inside your theme’s YOUR_THEME_DIR/js/cmw_script.js file. (Create this file if not exists)

    jQuery(function($) {
        $.post(
            cmw.ajaxurl,
            {
                "action": "",
                "product_id": 1122,
                "quantity": 1
            },
            function(data, status) {
                data = JSON.parse(data);
                if(data.added) {
                    window.alert("Product Added to cart");
                }
            }
        )
    });

    It’s Done!

    Using Ajax to load stuff asynchronously is pretty good idea. Use it to make your website better and faster.

    Do you know ?

    Using Ajax on WordPress reduces load on server as it reduces the number of reloads and loads only needed content.