WooCommerce related products by tag

This is my first post written in English and I am a bit nervous, because I am not a fluent writer/speaker yet. However, as the main goal of this blog is improve my English, let’s start the game.

This tip is oriented to change the way of related products of WordPress / WooCommerce stores are displayed. By default, related products are shown from relations category of products. But, my client wanted to control the feature using Tags. To get that, we have to make some changes. Let’s see:

1) At the child theme functions.php, I added a new function. The comments are self explanatory.


//New "Related Products" function for WooCommerce
function get_related_custom( $id, $limit = 5 ) {
    global $woocommerce;

    // Related products are found from category and tag
    $tags_array = array(0);
    $cats_array = array(0);

    // Get tags
    $terms = wp_get_post_terms($id, 'product_tag');
    foreach ( $terms as $term ) $tags_array[] = $term->term_id;

    // Get categories (removed / commented)
    $terms = wp_get_post_terms($id, 'product_cat');
    foreach ( $terms as $term ) $cats_array[] = $term->term_id;

    // Don't bother if none are set
    if ( sizeof($cats_array)==1 && sizeof($tags_array)==1 ) return array();

    // Meta query
    $meta_query = array();
    $meta_query[] = $woocommerce->query->visibility_meta_query();
    $meta_query[] = $woocommerce->query->stock_status_meta_query();

    // Get the posts
    $related_posts = get_posts( apply_filters('woocommerce_product_related_posts', array(
        'orderby'        => 'rand',
        'posts_per_page' => $limit,
        'post_type'      => 'product',
        'fields'         => 'ids',
        'meta_query'     => $meta_query,
        'tax_query'      => array(
            'relation'      => 'OR',
                'taxonomy'     => 'product_cat',
                'field'        => 'id',
                'terms'        => $cats_array
                'taxonomy'     => 'product_tag',
                'field'        => 'id',
                'terms'        => $tags_array
    ) ) );
    $related_posts = array_diff( $related_posts, array( $id ));
    return $related_posts;

2) After that, I copied the entire content of related.php (from theme > woocommerce > single-product > related.php) to a new file at child theme.

3) At last, I changed the call of function at related.php

a) of:

$related = $product->get_related($flatsome_opt['max_related_products']);

b) to:

$related = get_related_custom($product->id, $flatsome_opt['max_related_products']);

Voilá. It was easy, didn’t it? Now we have a new related products component that is filtered by tags.

See you later, with more articles about WordPress, Ruby on Rails and Django.