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

修改WooCommerce代码:实现用户购特定产品后触发指定文本显示

修改后的代码实现

以下是调整后的代码,仅在用户已登录、当前产品带有「Free」标签、且用户购买过指定产品三个条件同时满足时,才会显示指定文本:

function add_text_after_excerpt_single_product_free2( $short_description ) {
    global $product;
    
    // 未登录用户直接返回原描述
    if ( !is_user_logged_in() ) {
        return $short_description;
    }
    
    // 检查当前产品是否带有「Free」标签
    $has_free_tag = false;
    $terms = get_the_terms( $product->get_id(), 'product_tag' );
    if ( $terms && !is_wp_error( $terms ) ) {
        foreach ( $terms as $term ) {
            // 兼容标签名称大小写差异
            if ( strtolower( $term->name ) === 'free' ) {
                $has_free_tag = true;
                break;
            }
        }
    }
    
    // 无Free标签则返回原描述
    if ( !$has_free_tag ) {
        return $short_description;
    }
    
    // 替换为目标产品的ID(推荐用ID,比产品名称更稳定)
    $target_product_id = 123;
    // 若需通过产品名称获取ID,可使用:$target_product_id = wc_get_product_id_by_name( 'Photoshop training' );
    
    $current_user = wp_get_current_user();
    
    // 判断用户是否购买过目标产品
    if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $target_product_id ) ) {
        $short_description .= 'Downloading this file is free and does not require subscription';
    }
    
    return $short_description;
}
add_filter('woocommerce_short_description','add_text_after_excerpt_single_product_free2', 20, 1);

关键修改说明

  • 新增购买验证逻辑:使用WooCommerce内置函数wc_customer_bought_product(),直接验证当前登录用户是否购买过指定产品,优先用产品ID判断(避免产品名称修改导致逻辑失效)。
  • 优化执行效率:提前过滤未登录、无Free标签的情况,减少不必要的循环和判断。
  • 兼容大小写:将标签名称转为小写对比,避免因标签命名大小写不一致导致的逻辑失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:24:20