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

WooCommerce:修改加购按钮颜色、禁用缺货按钮及图标问题咨询

解决WooCommerce缺货商品“添加至结账”按钮的样式与点击禁用问题

首先得明确:你提供的这段代码是用来在商品循环(分类页/首页)的商品标题下方显示「Out of Stock」提示文本的,它不会直接修改缺货商品的“添加至结账”按钮样式和点击事件,所以没法解决你的核心问题哦。

针对你的需求——修改缺货按钮颜色、禁用点击,同时修复图标缺失的问题,我给你一套更精准的实现方案:

步骤1:用PHP钩子修改按钮属性与结构

我们可以借助WooCommerce的woocommerce_loop_add_to_cart_link钩子,拦截商品循环中“添加至结账”按钮的HTML输出,针对缺货商品做定制:

add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_out_of_stock_checkout_button', 10, 3 );
function custom_out_of_stock_checkout_button( $button_html, $product, $args ) {
    // 仅针对缺货商品处理
    if ( ! $product->is_in_stock() ) {
        // 给按钮添加自定义样式类,同时禁用点击跳转
        $button_html = str_replace( 'button', 'button out-of-stock-checkout-btn disabled', $button_html );
        $button_html = str_replace( 'href=', 'onclick="return false;" href=', $button_html );

        // 修复图标缺失:重新构建按钮HTML,手动加入图标(根据你的主题图标库调整代码)
        // 假设你用的是Font Awesome购物车图标,替换成你实际的图标代码即可
        $button_text = __( '添加至结账', 'woocommerce' );
        $button_html = sprintf(
            '<a href="%s" data-quantity="%s" class="%s" %s><i class="fa fa-shopping-cart"></i> %s</a>',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ),
            esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ) . ' out-of-stock-checkout-btn disabled',
            isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '',
            esc_html( $button_text )
        );
    }
    return $button_html;
}

步骤2:添加CSS自定义按钮颜色

把这段CSS代码添加到你的主题自定义CSS面板,或者主题的style.css文件中,设置缺货按钮的样式:

/* 缺货状态的添加至结账按钮样式 */
.out-of-stock-checkout-btn.disabled {
    background-color: #a0a0a0 !important; /* 自定义灰色背景,可替换成你想要的颜色 */
    color: #555 !important; /* 自定义文字颜色 */
    cursor: not-allowed; /* 鼠标悬停显示禁止图标 */
    pointer-events: none; /* 额外确保按钮无法被点击 */
    opacity: 0.7; /* 可选:添加半透明效果 */
}

补充说明

  1. 你原来的代码可以保留——它负责显示缺货提示文本,和新代码功能不冲突,能同时生效;
  2. 如果你的主题自定义了WooCommerce的按钮模板(比如主题目录下有woocommerce/loop/add-to-cart.php文件),那可能需要直接修改这个模板文件,把上述逻辑整合进去;
  3. 图标部分要根据你主题实际使用的图标库调整,比如主题自带的图标类名,替换代码里的<i class="fa fa-shopping-cart"></i>即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:41:22