简体   繁体   English

从Woocommerce的相关产品中排除特定产品

[英]Exclude specific products from related products in Woocommerce

In Woocommerce single product pages, I am trying to exclude any product that starts with the character 'I' from appearing in related products. 在Woocommerce单个产品页面中,我试图将任何以字符“ I”开头的产品排除在相关产品中。 I tried the following in single-product/related.php template file: 我在single-product/related.php模板文件中尝试了以下操作:

foreach($products as $product){
    if (substr($product->post_title, 0, 1) === 'I') {
          unset($product);
    }
}

But I'm still missing something as It doesn't work. 但是我仍然缺少一些东西,因为它不起作用。

How can I exclude products Ids which title start with the letter "I" from related products? 如何从相关产品中排除标题以字母"I"开头的产品ID?

Here is a little custom hooked function that will exclude product IDs Which title start with the letter "I" from related products in single product pages. 这是一个小的自定义挂钩函数,它将在单个产品页面的相关产品中排除标题以字母"I"开头的产品ID。

I use a very light SQL query to get those products IDs to be excluded. 我使用非常简单的SQL查询来获取要排除的那些产品ID。

The code: 编码:

add_filter( 'woocommerce_related_products', 'exclude_ids_from_related_products', 10, 3 );
function exclude_ids_from_related_products( $related_posts, $product_id, $query_args ){
    global $wpdb;

    $starting_by = "I"; // Excluding product title starting with…

    // Get all product IDs starting with "I" in an array to be excluded
    $excluded_ids = $wpdb->get_col( "
        SELECT ID FROM {$wpdb->prefix}posts WHERE post_type LIKE 'product'
        AND post_status LIKE 'publish' AND post_title LIKE '$starting_by%'
    " );

    // Return an array of related product IDs without excluded product IDs
    return array_diff ( $related_posts, $excluded_ids );
}

Code goes in function.php file of your active child theme (or active theme). 代码进入您的活动子主题(或活动主题)的function.php文件中。 Tested and works. 经过测试和工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM