在 Woocommerce 中使用简码显示带有动态产品 ID 的自定义按钮

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

我使用名为 Max Buttons 的 Wordpress 按钮插件来生成我想要的按钮。但是在那个按钮创建到 URL 需要指向按钮的地方只有 URL 需要指向按钮的地方。这看起来像这样:

如您所见,我使用 URL link 将优惠券代码自动更新到产品并重定向到结帐。但是,这是针对静态产品 ID 的。所以我的问题是如何为每个产品生成它,以在 URL 末尾自动获取产品 ID? MaxButton 插件在我插入到我想要的地方的地方生成简码。

当前 URL 是:

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

如何让 fill_cart=PRODUCT_ID 变得动态?

已更新 (对于简单和可变产品,使用 jQuery)

您可以使用 3 个参数构建自定义简码,例如 Max 按钮 (属性):

  • class(按钮的cssclass)
  • coupon(将在url中添加的优惠券代码)
  • text(按钮文字)

1) 代码 (CSS 样式嵌入在第一个函数中。jQuery 代码在页脚):

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
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。

2) 可能的简码用法:

  • 在产品 Wordpress post、自定义 post 或页面编辑器中:

    [max_btn class="flash-btn" coupon="5%off" text="Buy Now Get 5% off"]
    
  • 在 php 文件、模板或函数中:

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

    或(在html内):

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

生成的 html 代码类似于 (它也适用于变量产品):

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

可变产品:

当没有选择所有产品属性且未设置变体 ID 时,该按钮被禁用:

选择所有产品属性并设置变体 ID 后,按钮启用并闪烁: