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

如何在WooCommerce单产品页排除标题以‘I’开头的相关产品?

解决WooCommerce相关产品排除标题以‘I’开头的产品问题

嘿,我来帮你搞定这个问题~你之前的代码没生效是因为在foreach循环里unset($product)操作的只是数组元素的临时副本,根本不会修改原有的$products数组,所以那些产品还是会显示出来。下面给你两种靠谱的解决方法:

方法一:修改相关产品模板文件(适合习惯改模板的场景)

找到你的主题目录下的single-product/related.php文件,在原有的foreach循环之前,添加一段数组过滤的代码,把标题以‘I’开头的产品从数组中移除:

// 在foreach循环前添加这段代码
$products = array_filter($products, function($product) {
    // 如果你需要忽略大小写(比如排除以i或I开头的产品),可以改成strtolower(substr(...)) !== 'i'
    return substr(trim($product->post_title), 0, 1) !== 'I';
});

// 原有的foreach循环保留
foreach ( $products as $product ) {
    // 原模板里的产品输出代码...
}

这样过滤后的$products数组就不会包含标题以‘I’开头的产品了,相关产品区域自然就不会显示它们。

方法二:使用WooCommerce钩子(推荐,无需修改模板,便于后续更新)

这种方法不需要修改模板文件,直接在你的主题(或子主题)的functions.php文件中添加代码,通过WooCommerce的钩子来过滤相关产品:

方式A:过滤相关产品ID列表

add_filter('woocommerce_related_products', 'exclude_products_starting_with_i', 10, 3);
function exclude_products_starting_with_i($related_posts, $product_id, $args) {
    $filtered_ids = [];
    foreach($related_posts as $post_id) {
        $post_title = get_the_title($post_id);
        // 同样,要忽略大小写就改成strtolower(substr(trim($post_title), 0, 1)) !== 'i'
        if(substr(trim($post_title), 0, 1) !== 'I') {
            $filtered_ids[] = $post_id;
        }
    }
    return $filtered_ids;
}

方式B:直接修改数据库查询(更高效)

如果你的相关产品数量较多,这种方法在数据库层面就完成过滤,性能更好:

add_filter('woocommerce_related_products_query', 'exclude_i_starting_products_from_related_query');
function exclude_i_starting_products_from_related_query($query) {
    global $wpdb;
    // 添加SQL条件,排除标题以'I'开头的产品
    // 要忽略大小写的话,MySQL可以改成 AND LOWER({$wpdb->posts}.post_title) NOT LIKE 'i%'
    $query['where'] .= $wpdb->prepare(" AND {$wpdb->posts}.post_title NOT LIKE %s", 'I%');
    return $query;
}

两种钩子方法都能达到目的,推荐用方式B,因为它更高效,而且不需要循环获取每个产品的标题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:32:45