sort the related products by category and attribute in wordpress

  mysql, php, woocommerce, wordpress

I am new in wordpress and I want to show related products in product page by same category and sort by same attribute(attribute can be color,radius)etc. I am creating products using woo-commerece and using oxygen builder. Can anyone please help?

my query is

 function custom_query( $query) {
    global $product;
    $product_tags = get_the_terms($product->ID, 'product_cat');
    $product_tag_ids = array();

    foreach($product_tags as $product_tag){
        $product_tag_ids[] = $product_tag->term_id;

    $query->set(  'tax_query', array(array(
        'taxonomy'   =>  'product_cat',
        'field'      =>  'id',
        'terms'      =>  $product_tag_ids,

    ) );

    $query->set(  'orderby', 'rand');
    $query->set(  'attribute', 'type');
    $query->set( 'post_not_in', array($product->ID) );
    $query->set(  'no_found_rows', true);

Source: Ask PHP