2
votes

In Woocommerce single product pages, I am trying to exclude any product that starts with the character 'I' from appearing in related products. I tried the following in single-product/related.php template file:

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?

1

1 Answers

0
votes

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 use a very light SQL query to get those products IDs to be excluded.

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). Tested and works.