Skip to content

Wrong product url from getProductUrl when current category has not product object #17819

Description

@OleksiiBulba

Preconditions

  1. Install Magento 2.2.4
  2. Create two category category1 and category2 with url-keys category-1 and category-2 respectively
  3. Create product with url key product-1, assign it to category1
  4. Add created categories to topmenu (turn on "include to menu" checkbox)

Steps to reproduce

  1. Create custom module Vendor_Module; run setup:upgrade command
  2. Create template; add it to category layout
  3. In the template get product collection with all products in it
  4. In foreach loop try to get product url:
<?php foreach ($productCollection as $product): ?>
<? /** @var $product \Magento\Catalog\Model\Product */ ?>
<a href="<?= $product->getProductUrl() ?>"><?= $product->getName() ?></a>
<?php endforeach; ?>
  1. Open category2(!) page http://example.com/category-2

Expected result

  1. The product link should be like http://example.com/category-1/product-1

Actual result

  1. The product link is http://example.com/catalog/product/view/id/1/s/product-1/category/2

Possible reason

  1. In the file app/code/Magento/Catalog/Model/Product.php:695 (2.2 branch) product tries to get category from current_category;
  2. In the file app/code/Magento/Catalog/Model/Product/Url.php:163 (2.2 branch) Url model is searching for url rewrite for product1 from category2, but such rewrite does not exist because product1 does not belong to category2

Possible solution

  1. Check if retrieved category has product
  2. Add param to getProductUrl that specifies desired category in product url, for example:
<?php
$product->getProductUrl($category);
// or
$urlModel->getProductUrl($category, $product);

Metadata

Metadata

Labels

Component: CatalogFixed in 2.2.xThe issue has been fixed in 2.2 release lineFixed in 2.3.xThe issue has been fixed in 2.3 release lineIssue: Clear DescriptionGate 2 Passed. Manual verification of the issue description passedIssue: ConfirmedGate 3 Passed. Manual verification of the issue completed. Issue is confirmedIssue: Format is validGate 1 Passed. Automatic verification of issue format passedIssue: Ready for WorkGate 4. Acknowledged. Issue is added to backlog and ready for developmentReproduced on 2.2.xThe issue has been reproduced on latest 2.2 releaseReproduced on 2.3.xThe issue has been reproduced on latest 2.3 release

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions