Use custom taxonomy to select Related Products in Woocommerce

I have a woocommerce store with the two standard taxonomies – “categories” and “tags” – and a custom taxonomy “sport.” I have used the following code to focus Related Products on the “primary” category. ( Taken from this post: WooCommerce Related Products by children category as fallback to Rank Math Primary Category )

Now what I would like to do is to pick products that share the “custom taxonomy” “sport” rather than a “category.”

Is there a simple way to adapt this code to “sport” rather than “category” to select Related Products?

Thanks.

// Rank Math SEO - Use Primary Category for Related Products
add_filter( 'woocommerce_related_products', 'related_products_from_rank_math_primary_category', 10, 3 );
function related_products_from_rank_math_primary_category( $related_posts, $product_id, $args  ) {
    $taxonomy     = 'product_cat';
    $category_ids = wp_get_post_terms($product_id, $taxonomy, array('fields' => 'ids') ); 
    $term_slugs   = array(); // Initializing   

    if( count($category_ids) == 1 ) {
        // Get children categories
        $children_ids = get_term_children( reset($category_ids), $taxonomy );
        // Loop through children terms Ids
        foreach ( $children_ids as $tem_id ) {
            $term_slugs[] = get_term_by( 'id', $tem_id, $taxonomy )->slug; // get the slug from each term Id
        }
    } 
    elseif( count( $category_ids ) > 1 ) {
        // Get the primary category/term as saved by Rank Math SEO
        $primary_cat_id = get_post_meta( $product_id, 'rank_math_primary_product_cat', true );
        $term_slugs[]   = get_term_by( 'id', $primary_cat_id, $taxonomy )->slug; // get the slug from the term Id
    }

    if ( count($term_slugs) > 0 ) {
        // Product query: Get product Ids
        $related_posts = wc_get_products( array(
            'status'        => 'publish',
            'category'      => $term_slugs,
            'return'        => 'ids',
            'exclude'       => array( $product_id ),
            'visibility'    => 'catalog',
            'limit'         => -1,
        ) );
    }
    return $related_posts;
}

I tried replacing taxonomy=’product_cat’ with taxonomy=’sport’

That led the function to fail.

Leave a Comment