Search code examples
phpjquerycsswoocommerceshortcode

Display a custom button with a dynamic Product ID using a shortcode in Woocommerce


i using Wordpress button plugin called Max Buttons to generate button as i want. But in that button creation into URL where need to point button have only URL where need to point button. This looks like this:

enter image description here

So as you can see, i use URL link to autoupdate coupon code to product and redirect to checkout.. But, that is for static product ID. So my question is how to generate that to each product , to autoget product ID at end of URL? MaxButton plugin generate shortcode where i inserting into place where i want.

Current URL is:

https://testsite/checkout/?apply_coupon=5%off&fill_cart=4004

How to get that fill_cart=PRODUCT_ID to be dynamic?


Solution

  • Updated (for simple and variable products, using jQuery)

    You can build a custom shortcode like Max buttons with 3 arguments (attributes):

    • class (the css class of the button)
    • coupon (the coupon code that will be added in the url)
    • text (the button text)

    1) The code (The CSS styles are embedded in the 1st function. The jQuery code is in the footer):

    add_shortcode('max_btn', 'custom_dynamic_max_button');
    function custom_dynamic_max_button( $atts ) {
        if( ! is_product() ) return; // exit
        global $post;
    
        // Shortcode attributes
        $atts = shortcode_atts(
            array(
                'class'   => '',
                'coupon'  => '',
                'text'    => '',
            ),
        $atts, 'max_btn');
    
        // Formatting CSS class
        $class = ! empty($atts['class']) ? 'max-btn ' . $atts['class'] : 'max-btn';
    
        // Format the coupon code if it's set as an argument
        $coupon = ! empty($atts['coupon']) ? 'apply_coupon=' . $atts['coupon'] . '&' : '';
    
        // Format the url with the dynamic Product ID
        $link = wc_get_checkout_url() . '?' . $coupon . 'fill_cart=' . $post->ID;
    
        // The button code:
        ob_start();
        ?>
        <style>
        .max-btn.flash-btn {
            position: relative;
            text-decoration: none;
            display: inline-block;
            vertical-align: middle;
            border-color: #ef2409;
            width: 225px;
            height: 43px;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
            border-bottom-left-radius: 4px;
            border-bottom-right-radius: 4px;
            border-style: solid;
            border-width: 2px;
            background-color: rgba(239, 36, 9, 1);
            -webkit-box-shadow: 0px 0px 2px 0px #333;
            -moz-box-shadow: 0px 0px 2px 0px #333;
            box-shadow: 0px 0px 2px 0px #333;
            color: #c8146e;
        }
        .max-btn.flash-btn {
            animation-name: flash;
            animation-duration: 1s;
            animation-timing-function: linear;
            animation-iteration-count: infinite;
            -webkit-animation-name: flash;
            -webkit-animation-duration: 1s;
            -webkit-animation-timing-function: linear;
            -webkit-animation-iteration-count: infinite;
            -moz-animation-name: flash;
            -moz-animation-duration: 1s;
            -moz-animation-timing-function: linear;
            -moz-animation-iteration-count: infinite;
        }
        .max-btn:hover.flash-btn {
            border-color: #505ac7;
            background-color: rgba(255, 255, 255, 1);
            -webkit-box-shadow: 0px 0px 2px 0px #333;
            -moz-box-shadow: 0px 0px 2px 0px #333;
            box-shadow: 0px 0px 2px 0px #333;
        }
        @keyframes flash {
            0% { opacity: 1.0; }
            50% { opacity: 0.5; }
            100% { opacity: 1.0; }
        }
        @-moz-keyframes flash {
            0% { opacity: 1.0; }
            50% { opacity: 0.5; }
            100% { opacity: 1.0; }
        }
        .max-btn.flash-btn > .mb-text {
            color: #fff;
            font-family: Tahoma;
            font-size: 20px;
            text-align: center;
            font-style: normal;
            font-weight: bold;
            padding-top: 11px;
            padding-right: 0px;
            padding-bottom: 0px;
            padding-left: 0px;
            line-height: 1em;
            box-sizing: border-box;
            display: block;
            background-color: unset;
            outline: none;
        }
        .max-btn:hover.flash-btn > .mb-text {
            color: #505ac7;
        }
    
        .max-btn.disabled,
        .max-btn:hover.disabled {
            cursor: not-allowed;
            background-color: rgba(160, 160, 160, 1) !important;
            border-color: rgba(160, 160, 160, 1) !important;
            animation-name: unflash !important;
            -webkit-animation-name: unflash !important;
            -moz-animation-name: unflash !important;
        }
        .max-btn:hover.flash-btn.disabled > .mb-text {
            color: #fff !important;
        }
        </style>
        <a class="<?php echo $class; ?>" href="<?php echo $link; ?>">
            <span class="mb-text"><?php echo $atts['text']; ?></span>
        </a>
        <input type="hidden" class="ccoupon" name="ccoupon" value="<?php echo $atts['coupon']; ?>">
        <?php
    
        return ob_get_clean(); // Output
    }
    
    
    add_action('wp_footer','custom_jquery_single_product_script');
    function custom_jquery_single_product_script(){
        // Only for single product pages
        if ( ! is_product() ) return;
    
        // Get an instance of the WC_Product object
        $product = wc_get_product(get_the_id());
    
        // Only for variable products
        if( ! $product->is_type('variable') ) return;
    
        // Pass the partial link to jQuery
        $partial_link = wc_get_checkout_url() . '?';
    
        ?>
        <script type="text/javascript">
        (function($){
            // variables initialization
            var a = '<?php echo $partial_link; ?>',
                b = 'input[name="variation_id"]',
                c = 'a.max-btn.flash-btn',
                d = '.variations select',
                e = 'input.ccoupon';
    
            // Get the partial link (without the product ID)
            if( $(e).val() != '' )
                a += 'apply_coupon=' + $(e).val() + '&fill_cart=';
            else
                a += 'fill_cart=';
    
            // Utility function to enable button with the correct variation ID
            function enableButton(){
                // Set the correct URL with the dynamic variation ID and remove "disable" class
                $(c).attr("href", a+$(b).val()).removeClass('disabled');
            }
    
            // Utility function to disable button
            function disableButton(){
                // Remove href attribute and set "disable" class
                $(c).removeAttr('href').addClass('disabled');
            }
    
            // -- 1. Once DOM is loaded
    
            // Remove href attribute and set "disable" class
            disableButton();
            // If variation ID exist, we enable the button with the correct variation ID
            setTimeout(function(){
                if($(b).val() > 0)
                    enableButton();
            }, 800);
    
            // -- 2. On live events
    
            // On product attribute select fields "blur" event
            $(d).blur( function(){
                // If variation ID exist (all product attributes are selected)
                if( $(b).val() > 0 )
                    enableButton();
                // If variation ID doesn't exist (all product attributes are NOT selected)
                else
                    disableButton();
    
                console.log('select: '+$(b).val());
            });
        })(jQuery);
        </script>
        <?php
    }
    

    Code goes in function.php file of your active child theme (or active theme).

    2) Possible shortcode USAGE:

    • In the product Wordpress post, custom post or page editor:

      [max_btn class="flash-btn" coupon="5%off" text="Buy Now Get 5% off"]
      
    • In a php file, template or function:

      echo do_shortcode('[max_btn class="flash-btn" coupon="5%off" text="Buy Now Get 5% off"]');
      

      Or (inside html):

      <?php echo do_shortcode('[max_btn class="flash-btn" coupon="5%off" text="Buy Now Get 5% off"]'); ?>
      

    The generated html code will be something like (and it works for variable products too):

    <a class="max-btn flash-btn" href="http://www.example.com/checkout/?apply_coupon=5%off&amp;fill_cart=37">
        <span class="mb-text">Buy Now Get 5% off</span>
    </a>
    <input type="hidden" class="ccoupon" name="ccoupon" value="5%off">
    

    The Url will be auto generated with a dynamic product ID on single product pages.
    Tested and works.

    For variable products:

    When all the product attributes are not selected and the variation ID is not set, the button is disabled:

    enter image description here

    When all the product attributes are selected and the variation ID is set, the button is enabled and blink:

    enter image description here