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

标签 php jquery css woocommerce shortcode

我使用名为 Max Button 的 WordPress 按钮插件s 根据我的需要生成按钮。但是在该按钮创建到需要指向按钮的 URL 时,只有需要指向按钮的 URL。看起来像这样:

enter image description here

正如您所看到的,我使用 URL 链接将优惠券代码自动更新到产品并重定向到结账。但是,这是针对静态产品 ID 的。所以我的问题是如何为每个产品生成它,以在 URL 末尾自动获取产品 ID? MaxButton 插件生成短代码,我可以将其插入到我想要的位置。

当前网址是:

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

如何使 fill_cart=PRODUCT_ID 变得动态?

最佳答案

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

您可以构建一个自定义短代码,例如带有 3 个参数的 Max 按钮(属性):

  • class(按钮的 css 类)
  • 优惠券(将添加到网址中的优惠券代码)
  • 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 帖子、自定义帖子或页面编辑器中:

    [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 时,该按钮被禁用:

enter image description here

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

enter image description here

关于php - 在 Woocommerce 中使用短代码显示带有动态产品 ID 的自定义按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50085349/

相关文章:

php - HTML 中链接标签的正则表达式

jquery - 与 jQuery 绑定(bind)时,DOM 更改不会实时反射(reflect)

javascript - 在页面加载时动画对象,但仍然能够随着悬停而改变

css - 当有足够的空间时,Flexbox 将一个 div 放置在其他 div 的右侧

php - 如何获取 PHP 脚本以将数据馈送到 JQuery 自动完成中?

php - 在排名搜索查询中指定排名 PHP、MySQL

php - 易受 SQL 注入(inject)攻击的 GET 参数 - PHP

javascript - jQuery 获取非空输入值之一

javascript - 如何使用 CSS 将 HTML 元素干净地放在同一行

javascript - CSS 表 : colspan row to full table width