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

修改WooCommerce用户购买后加入购物车按钮的文本与链接

解决方案

要实现将已购买课程的"加入购物车"按钮替换为指向账户下载页的链接,仅修改按钮文字是不够的——还需要替换按钮的HTML结构,因为默认按钮是表单提交元素。以下是完整的实现代码:

// 替换归档产品页的添加到购物车按钮
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_bought_product_add_to_cart_link', 900, 3 );
// 替换单产品页的添加到购物车按钮
add_action( 'woocommerce_single_product_summary', 'custom_replace_single_add_to_cart_button', 1 );

function custom_bought_product_add_to_cart_link( $button_html, $product, $args ) {
    $current_user = wp_get_current_user();
    
    // 仅针对已登录且购买过该产品的用户修改按钮
    if ( is_user_logged_in() && wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->get_id() ) ) {
        $download_url = wc_get_account_endpoint_url( 'downloads' ); // 获取账户下载页的正确URL
        $button_text = __( "查看下载文件", "woocommerce" );
        
        // 构建新的链接按钮HTML
        $button_html = sprintf( '<a href="%s" class="button %s">%s</a>',
            esc_url( $download_url ),
            esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ),
            esc_html( $button_text )
        );
    }
    
    return $button_html;
}

function custom_replace_single_add_to_cart_button() {
    global $product;
    $current_user = wp_get_current_user();
    
    if ( is_user_logged_in() && wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->get_id() ) ) {
        // 移除默认的添加到购物车按钮
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
        // 添加自定义链接按钮
        add_action( 'woocommerce_single_product_summary', 'custom_single_bought_product_download_link', 30 );
    }
}

function custom_single_bought_product_download_link() {
    $download_url = wc_get_account_endpoint_url( 'downloads' );
    $button_text = __( "查看下载文件", "woocommerce" );
    
    echo sprintf( '<a href="%s" class="single_add_to_cart_button button alt">%s</a>',
        esc_url( $download_url ),
        esc_html( $button_text )
    );
}

代码说明:

  • 针对归档产品页,用woocommerce_loop_add_to_cart_link过滤器直接替换按钮HTML为跳转链接。
  • 针对单产品页,先判断用户购买状态,若已购买则移除默认表单按钮,添加自定义跳转链接。
  • 用wc_get_account_endpoint_url('downloads')获取官方标准的下载页地址,避免硬编码路径导致的兼容性问题。
  • 加入is_user_logged_in()判断,防止未登录用户看到异常按钮状态。

使用注意:

  1. 将代码添加到主题functions.php文件或自定义插件中即可生效。
  2. 测试时请确保用户已登录且确实购买过对应课程。
  3. 若需要调整按钮样式,可修改代码中class属性的值,匹配你的主题样式规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:25:16