Blog

  • How to Exclude a Product from Discount Coupons in WooCommerce with PHP Snippet

    Discover how to exclude specific products from discount coupons in WooCommerce using a PHP snippet. By following these steps, you’ll have more control over your coupon promotions and ensure a seamless shopping experience for your customers.

    Step 1: Locate the PHP File Open your theme’s functions.php file or create a custom plugin for code snippets.

    Step 2: Implement the PHP Snippet Copy and paste the PHP code provided below into the functions.php file or your custom plugin.

    function exclude_product_from_coupons( $excluded, $product ) {
        $excluded_products = array( 123 ); // Replace 123 with the product ID you want to exclude
    
        if ( in_array( $product->get_id(), $excluded_products ) ) {
            $excluded = true;
        }
    
        return $excluded;
    }
    add_filter( 'woocommerce_coupon_is_valid_for_product', 'exclude_product_from_coupons', 10, 2 );

    Step 3: Define the Product to Exclude In the PHP snippet, replace 123 with the actual product ID you want to exclude from discount coupons. Find the product ID by editing the product in the WooCommerce admin area and checking the URL.

    Step 4: Save and Activate Save the changes to the functions.php file or your custom plugin. The exclusion functionality will now be active.

  • 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!

  • Create a Custom Post Type in WordPress with PHP Snippets

    Creating a custom post type in WordPress can be a great way to organize your content and make it easier for your visitors to find what they’re looking for. In this post, we’ll walk you through the steps to create a custom post type in WordPress using PHP snippets.

    Step 1: Open functions.php To create a custom post type for movies in WordPress using PHP snippets, 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 create a custom post type for movies:

    function custom_post_type_movies() {
        $labels = array(
            'name' => 'Movies',
            'singular_name' => 'Movie',
            'menu_name' => 'Movies',
            'parent_item_colon' => 'Parent Movie:',
            'all_items' => 'All Movies',
            'view_item' => 'View Movie',
            'add_new_item' => 'Add New Movie',
            'add_new' => 'Add New',
            'edit_item' => 'Edit Movie',
            'update_item' => 'Update Movie',
            'search_items' => 'Search Movie',
            'not_found' => 'Not found',
            'not_found_in_trash' => 'Not found in Trash',
        );
        $args = array(
            'label' => 'movies',
            'description' => 'Movies Description',
            'labels' => $labels,
            'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
            'taxonomies' => array( 'category', 'post_tag' ),
            'hierarchical' => false,
            'public' => true,
            'show_ui' => true,
            'show_in_menu' => true,
            'menu_position' => 5,
            'show_in_admin_bar' => true,
            'show_in_nav_menus' => true,
            'can_export' => true,
            'has_archive' => true,
            'exclude_from_search' => false,
            'publicly_queryable' => true,
            'capability_type' => 'post',
        );
        register_post_type( 'movies', $args );
    }
    add_action( 'init', 'custom_post_type_movies', 0 );

    This code creates a custom post type called “Movies” with a label, description, and various other settings. 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 custom post type. You should now see a new menu item in your WordPress dashboard called “Movies” where you can add, edit, and delete movie posts.

    Remember to optimize your movie posts for SEO by using relevant keywords in your post titles, descriptions, and content. By doing so, you can improve your site’s visibility in search engine results and attract more visitors to your site.

    We hope you found this example 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.

  • Sorry, this file type is not permitted for security reasons.

    If you’re facing the “Sorry, this file type is not permitted for security reasons” error in WordPress, and none of the standard solutions have worked for you, there is another option you can try. You can add a line of code to your wp-config.php file that will allow unfiltered uploads. Here’s how to do it:

    1. Log in to your WordPress site and go to the root folder of your website.
    2. Find the wp-config.php file and open it in a text editor.
    3. Add the following line of code to the file, preferably just above the “/* That’s all, stop editing! Happy blogging. */” line:
    define( 'ALLOW_UNFILTERED_UPLOADS', true );
    1. Save the file and re-upload it to your server, overwriting the original file.

    Once you’ve added this line of code and saved the file, you should be able to upload any file type to your WordPress site without encountering the “Sorry, this file type is not permitted for security reasons” error.

    However, it’s important to note that allowing unfiltered uploads can be a security risk, as it removes some of the built-in security features of WordPress. So, use this solution with caution and only if you know what you’re doing.

    In summary, if you need to allow unfiltered uploads in WordPress, you can add the line “define( ‘ALLOW_UNFILTERED_UPLOADS’, true );” to your wp-config.php file. This should allow you to upload any file type without encountering the “Sorry, this file type is not permitted for security reasons” error. But keep in mind that this can be a security risk, so use it with caution.

  • 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.