【问题标题】:Display a WooCommerce coupon input field anywhere with a shortcode使用简码在任何地方显示 WooCommerce 优惠券输入字段
【发布时间】:2019-08-10 08:09:12
【问题描述】:

我有一个小项目,我需要将 Woocommerce 优惠券字段插入任何页面,但这对我来说似乎很复杂。我在谷歌上搜索过这个,但没有任何关于这个的资源。找到有关插入字段的代码。

将此代码插入到文本块中:

<div class="redeem-coupon">
<form id="ajax-coupon-redeem">
    <p>
        <input type="text" name="coupon" id="coupon"/>
        <input type="submit" name="redeem-coupon" value="Redeem Offer" />
    </p>
    <p class="result"></p>
</form><!-- #ajax-coupon-redeem -->

这会生成表单,但没有其他代码可以将其处理到页面中?

是否可以通过短代码或其他方式生成?

【问题讨论】:

    标签: php wordpress woocommerce shortcode coupon


    【解决方案1】:

    以下自定义短代码将显示一个文本输入字段(带有提交按钮),用户可以在其中输入要应用的优惠券代码。

    用法:[coupon_field] 或 PHP 代码 echo do_shortcode("[coupon_field]");

    代码:

    add_shortcode( 'coupon_field', 'display_coupon_field' );
    function display_coupon_field() {
        if( isset($_GET['coupon']) && isset($_GET['redeem-coupon']) ){
            if( $coupon = esc_attr($_GET['coupon']) ) {
                $applied = WC()->cart->apply_coupon($coupon);
            } else {
                $coupon = false;
            }
    
            $success = sprintf( __('Coupon "%s" Applied successfully.'), $coupon );
            $error   = __("This Coupon can't be applied");
    
            $message = isset($applied) && $applied ? $success : $error;
        }
    
        $output  = '<div class="redeem-coupon"><form id="coupon-redeem">
        <p><input type="text" name="coupon" id="coupon"/>
        <input type="submit" name="redeem-coupon" value="'.__('Redeem Offer').'" /></p>';
    
        $output .= isset($coupon) ? '<p class="result">'.$message.'</p>' : '';
    
        return $output . '</form></div>';
    }
    

    代码在您的活动子主题(或主题)的 function.php 文件中。经过测试并且可以工作。

    应用优惠券后会显示成功或错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      • 2014-11-26
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      相关资源
      最近更新 更多