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

修改WooCommerce单品页Add to Cart按钮:已购用户替换链接与标签

适配WooCommerce单品页的已购产品按钮修改方案

原代码仅通过woocommerce_loop_add_to_cart_link钩子处理店铺循环页的按钮,而单品页的Add to Cart按钮使用不同的钩子体系,因此需要补充对应逻辑。以下是完整修改后的代码:

// 检查客户是否已购买产品(仅针对已完成状态的订单)
// 处理店铺循环页(Shop Page)的按钮
add_filter('woocommerce_loop_add_to_cart_link', 'custom_add_to_cart_link_for_bought_products', 10, 2);
function custom_add_to_cart_link_for_bought_products($html, $product) {
    // 获取当前用户
    $current_user = wp_get_current_user();
    
    // 检查用户是否已购买该产品
    if (wc_customer_bought_product($current_user->user_email, $current_user->ID, $product->get_id())) {
        $product_url = "https://editorials.in/package/onlinecoaching/";
        $button_label = "View Lecture";
        
        // 重新生成按钮HTML
        $html = sprintf('<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
            esc_url($product_url),
            esc_attr($product->get_id()),
            esc_attr($product->get_sku()),
            esc_attr(isset($quantity) ? $quantity : 1),
            $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
            esc_attr($product->get_type()),
            esc_html($button_label)
        );
    }
    
    return $html;
}

// 处理单品页(Single Product Page)的按钮文本
add_filter('woocommerce_product_single_add_to_cart_text', 'custom_single_add_to_cart_text_for_bought_products', 10, 1);
function custom_single_add_to_cart_text_for_bought_products($text) {
    global $product;
    
    if (!$product) return $text;
    
    $current_user = wp_get_current_user();
    
    if (wc_customer_bought_product($current_user->user_email, $current_user->ID, $product->get_id())) {
        $text = "View Lecture";
    }
    
    return $text;
}

// 处理单品页(Single Product Page)的按钮链接
add_filter('woocommerce_get_add_to_cart_url', 'custom_single_add_to_cart_url_for_bought_products', 10, 2);
function custom_single_add_to_cart_url_for_bought_products($url, $product) {
    $current_user = wp_get_current_user();
    
    if (wc_customer_bought_product($current_user->user_email, $current_user->ID, $product->get_id())) {
        $url = "https://editorials.in/package/onlinecoaching/";
    }
    
    return $url;
}

代码修正要点

  • 改用WooCommerce官方推荐的$product->get_id()、$product->get_type()方法,适配新版插件规范,替换原代码中过时的$product->id写法。
  • 新增两个单品页专属钩子,分别控制按钮文本和跳转链接,确保单品页逻辑与循环页一致。
  • 移除原代码中未定义$id变量的错误逻辑,避免PHP运行报错。
  • 统一使用wc_customer_bought_product函数判断用户购买状态,保证两处页面的判断规则完全相同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:15:42