Get Magento product from url key
-
12-04-2021 - |
Question
I want to get product details from url key.
Is there a way to get product details from url_key, I am new to Magento and could not find any such way, please help I tried below code but it is not working properly.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$storeIds = array_keys($storeManager->getStores());
$action = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Action');
while($row = mysqli_fetch_assoc($result)) {
$updateAttributes = array();
echo $row["slug"];
echo "--->";
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToFilter('url_key',"URL_KEY_HERE");
$collection->addAttributeToSelect('*');
foreach ($collection as $product)
{
echo "id is ->".$product->getId();
echo "<br>";
}
}
La solution
$urlKey = "strive-shoulder-pack"; // add your url key which you want
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\Collection');
$productCollectionFactory->addAttributeToFilter('url_key',$urlKey);
$productCollectionFactory->addAttributeToSelect('*');
foreach ($productCollectionFactory as $product)
{
echo "id is ->".$product->getId();
echo "<br>";
print_r($product->getData());
echo "<br>";
}
Note: Only Enable Product url can check so please enter proper enable product url key
Autres conseils
For getting product details from url key using ObjectManager:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$prodColl = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$collection = $prodColl->addAttributeToSelect('*')
->addAttributeToFilter('url_key','joust-duffle-bag');
echo '<pre>';
print_r($collection->getData());
echo '</pre>';
firstly don't use objectManager you can inject the used class in the construct:
public function __construct(\Magento\Catalog\Model\ProductFactory $productFactory)
{
$this->productFactory = $productFactory;
}
And after that in your class use loadByAttribute function
$product = $this->productFactory->create();
$product->loadByAttribute('url_key', $urlKey);
I want my answer to help you
With ObjectManager:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
$product = $productFactory->create();
$product->loadByAttribute('url_key', $urlKey);
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange