I want to get product url with category key in it on home page.
for example:
www.example.com/category/product.html
Thanks
I want to get product url with category key in it on home page.
for example:
www.example.com/category/product.html
Thanks
If you have a product collection, you will need to specify a category for each product in the collection.
If you are using a category collection the category from the collection will be used.
The product you are generating a URL for will need to know which category it should include in the url, which is why if you just load the product without mentioning a category, you will not return any category in the path even if you adjust the admin settings like others have recommended.
Some psuedo code to get you started:
// Taken from https://stackoverflow.com/questions/18300258/magento-getproducturl-does-not-include-category-path
$product->setCategoryId($categoryId)->getProductUrl();
$product->setCategoryId(max($product->getCategoryIds()))->getProductUrl();
- that ways I get a product url wih the deepest category for a product.
go to Store -> Configuration -> Catalog -> Catalog -> Search Engine Optimization -> "Use Categories Path for Product URLs" set to "Yes"
After that Reindex using php bin/magento indexer:reindex
I used the below code today for a similar thing
public function __construct(
...
\Magento\Framework\Registry $registry,
\Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
\Magento\Store\Model\StoreManagerInterface $storeManager
...
) {
...
$this->storeManager = $storeManager;
$this->registry = $registry;
$this->categoryRepository = $categoryRepository;
...
}
...
$categoryIds = $product->getCategoryIds();
if (!$categoryIds) {
return null;
}
$category = $this->categoryRepository->get($categoryIds[0], $this->storeManager->getStore()->getId());
$this->registry->register('current_category',$category);
$redirectionUrl = $product->getProductUrl();
...
I did this by using following code
<?php $_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); ?>
<?php $cats = $_item->getCategoryIds();
if(count($cats) ){
if($cats[0]==2){
$firstCategoryId = $cats[1];
}
else{
$firstCategoryId = $cats[0];
}
$_category = $_objectManager->create('Magento\Catalog\Model\Category')->load($firstCategoryId);
$categorykey = $_category->getUrlKey();
$siteurl= $block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
$pro_url=$siteurl.$categorykey."/".$_item->getUrlKey().".html";
}
else{
$pro_url=$block->getProductUrl($_item);
}
?>