Web Design
January 21, 2024
Kyle

Dynamically Display Sale Percentages in Elementor Loops with Custom Shortcode

Unlock the potential of your eCommerce site with Elementor by adding dynamic sale percentage badges using custom shortcodes and JavaScript for an engaging shopping experience.
Share
Reddit
Twitter
Facebook
LinkedIn
Email
Print

Table of Contents

Share

Introduction

Boosting eCommerce Visuals: Dynamic Sale Percentage Badges in Elementor

As the digital marketplace burgeons, online shops must leverage every tool to stand out. That’s where Elementor and some clever coding come into play. Today, we’ll dive deep into how to create a dynamic visual cue—a sale percentage badge—using a custom shortcode and JavaScript to ensure your product loops are not just informative, but visually compelling.

The Issue at Hand

When browsing products, customers love a good sale. But if that sale isn’t noticeable, they might scroll right past. What if there was a way to not only tell your customers how much they’re saving but also to draw their attention visually?

The PHP: Crafting the Shortcode

We begin with PHP to create the shortcode [sale_percentage], which calculates the sale percentage of a product. Here’s how it works:

				
					function calculate_sale_percentage() {
    // Get the current post object
    $post = get_post();

    // If it's not a product, return an empty string
    if ($post->post_type !== 'product') return '';

    // Get an instance of the WC_Product object
    $product = wc_get_product($post->ID);

    // If we don't have a valid product object, return an empty string
    if (!$product) return '';

    // Initialize output
    $output = '';

    if ($product->is_type('variable')) {
        // Handle variable products
        $regular_price = $product->get_variation_regular_price('min');
        $sale_price = $product->get_variation_sale_price('min');
    } else {
        // Handle simple and other types of products
        $regular_price = $product->get_regular_price();
        $sale_price = $product->get_sale_price();
    }

    // Check if the product is on sale and regular price is greater than 0
    if ($product->is_on_sale() && $regular_price > 0) {
        $percentage = round(((($regular_price - $sale_price) / $regular_price) * 100));

        // Create output with classes for styling
        $output = '<div class="sale-badge">';
        $output .= '<span class="sale-value">' . $percentage . '</span>';
        $output .= '<span class="sale-percentage">%</span>';
        $output .= '<span class="sale-text"> Off</span>';
        $output .= '</div>';
    }

    // Return the output
    return $output;
}

add_shortcode('sale_percentage', 'calculate_sale_percentage');
				
			

This function fetches the product’s regular and sale prices, calculates the discount percentage, and then wraps it up in a neat little HTML package with classes for styling.

Usage in Elementor:

Simply place the [sale_percentage] shortcode into a Text Editor or Heading widget within your Elementor Loop template. (This way you can also easily style the text within Elementor)

The JavaScript: Adding Color to Savings

Now that the savings are clear, let’s add some color. Our JavaScript will color-code the discount badges based on the percentage value, making higher discounts more prominent.

				
					<script>window.addEventListener('DOMContentLoaded', function() {

jQuery(document).ready(function($) {
    $('.sale-container .elementor-widget-container').each(function() {
        // Find the sale value inside this container
        let saleValue = $(this).find('.sale-value').text();

        if(!saleValue) return; // Skip if no sale value found

        saleValue = parseInt(saleValue);

        if(isNaN(saleValue) || saleValue < 0) return; // Skip if sale value is not a valid positive number

        // Color codes based on your design preference
        let colors = [
            { threshold: 20, color: '#B2DFDB' }, // Light Teal
            { threshold: 30, color: '#FFD54F' }, // Bright Yellow
            { threshold: 40, color: '#FF8A65' }, // Light Coral
            { threshold: 50, color: '#61CE70' }, // Green
            { threshold: 60, color: '#BBDEFB' }, // Light Blue
            { threshold: 70, color: '#D7CCC8' }  // Light Brown
        ];

        // Select color based on saleValue
        let selectedColor = colors.reduce((selected, current) => {
            return saleValue >= current.threshold ? current.color : selected;
        }, '#61CE70'); // Green as the default color

        // Set the background color of the elementor-widget-container
        $(this).css('backgroundColor', selectedColor);
    });
});



});</script>
				
			

This script iterates over each product, checks the sale percentage, and applies a background color accordingly. The goal? Instant visual comprehension of the deal’s sweetness.

Integration into Elementor

For the PHP, add the code to your theme’s functions.php file or a site-specific plugin. For the JavaScript, you can add it directly into Elementor’s Custom Code feature (if you’re using Elementor Pro) or via a plugin that allows custom scripts.

Why Does This Matter?

In an era where online shopping is king, standing out is paramount. A visual representation of savings can psychologically influence purchasing decisions. It’s about making the shopping experience as intuitive and engaging as possible.

In Conclusion

Creating dynamic, visually stimulating elements on your website is key in the crowded online marketplace. By integrating these snippets into your Elementor website, you’re not just coding; you’re crafting an experience.

Final Thoughts

Empowering your eCommerce site with custom features like dynamic sale badges doesn’t just serve an aesthetic purpose—it also aligns with strategic marketing and user experience best practices. By following this tutorial, you’re not just editing a website; you’re enhancing the way customers interact with your products.