You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery+PHP实现按钮点击切换商品原价与自定义优惠价

实现方案

你只需要修改原有JS逻辑,新增原价存储变量、双向切换分支即可,完整修改后代码如下:

// 添加bestprice自定义字段
$bestprice = get_post_meta( $product->get_id(), '_bestprice', true);

if( ! empty($bestprice) ):
    $bestprice = wc_get_price_to_display( $product, array( 'price' => $bestprice ) );
    $reg_price = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );
    $range = wc_format_sale_price( $reg_price, $bestprice );
?>
<!-- 按钮和隐藏域结构 -->
<div class="bestprice-wrapper"><br>
    <a href="" class="get_bestprice button alt" id="get_bestprice"><?php _e('Aktivovat lepší cenu');?></a>
    <input type="hidden" name="bestprice" id="bestprice" class="bestprice" value="" />
</div>
<!-- 修改后的jQuery切换逻辑 -->
<script type="text/javascript">
    (function($){
        var b = '<?php echo $bestprice; ?>',
            i = 'input[name=bestprice]',
            p = 'p.price',
            r = '<?php echo $range; ?>',
            t = 'a#get_bestprice',
            // 存储页面初始加载时的常规原价HTML
            origin_price = $(p).html(),
            // 状态标记:true=当前显示原价,false=当前显示优惠价
            show_origin = true;
        $(t).click( function(e){
            e.preventDefault();
            if(show_origin){
                // 切换为优惠价逻辑
                $(p).html(r);
                $(i).val(b);
                $(t).text('Activated');
                $(t).removeClass('alt get_bestprice');
                $(t).addClass('afterclickbutton');
                show_origin = false;
            }else{
                // 切换回原价逻辑
                $(p).html(origin_price);
                $(i).val('');
                $(t).text('<?php _e('Aktivovat lepší cenu');?>');
                $(t).removeClass('afterclickbutton');
                $(t).addClass('alt get_bestprice');
                show_origin = true;
            }
        });
    })(jQuery);
</script>
<?php
endif;
修改说明
  • 新增origin_price变量,页面加载时就保存原始的价格显示内容,切换回原价时直接调用即可
  • 把原来的单次触发逻辑改成了双向切换,show_origin变量作为状态标记控制两种显示模式
  • 恢复原价时同步重置了隐藏域值、按钮文本和样式类,保证逻辑回到初始状态可以再次切换
  • 修复了原代码中错误的全角引号问题,避免JS执行报错

内容的提问来源于stack exchange,提问作者VJay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:54:03