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