How to set related products view contextual filter to get its value from current product category id
I needed a block to display related products for the current viewed product by showing products from the same category.

To do that you can use the same steps used in the 'related article' tutorial.

but first you have to add the ability to extract term id from product page (like the way it is extracted from node page), so you have to modify

core\modules\taxonomy\src\Plugin\views\argument_default\Tid.php


like this

include this namespace:

use Drupal\commerce_product\Entity\ProductInterface;


look for:

    else {
      return implode($this-&gt;options['anyall'], array_keys($taxonomy));
    }
  }


replace with:

    else {
      return implode($this-&gt;options['anyall'], array_keys($taxonomy));
    }
  } elseif (($product = $this-&gt;routeMatch-&gt;getParameter('commerce_product')) &amp;&amp; $product instanceof ProductInterface) {
    $taxonomy = [];
    foreach ($product-&gt;getFieldDefinitions() as $field) {
      if ($field-&gt;getType() == 'entity_reference' &amp;&amp; $field-&gt;getSetting('target_type') == 'taxonomy_term') {
        $taxonomy_terms = $product-&gt;{$field-&gt;getName()}-&gt;referencedEntities();
        /** @var \Drupal\taxonomy\TermInterface $taxonomy_term */
        foreach ($taxonomy_terms as $taxonomy_term) {
          $taxonomy[$taxonomy_term-&gt;id()] = $taxonomy_term-&gt;bundle();
        }
      }
    }
    if (!empty($this-&gt;options['limit'])) {
      $tids = [];
      // filter by vocabulary
      foreach ($taxonomy as $tid =&gt; $vocab) {
        if (!empty($this-&gt;options['vids'][$vocab])) {
          $tids[] = $tid;
        }
      }
      return implode($this-&gt;options['anyall'], $tids);
    }
    // Return all tids.
    else {
      return implode($this-&gt;options['anyall'], array_keys($taxonomy));
    }
  }