2

Currently I have this in list.phtml file:

echo $_product->getProductUrl()

What I need is just the url key, not the full url. How can I achieve that in Magento 2 as getUrlKey() does not seem to work there.

UPDATE

Here is the code of my list to the point where the url key would be needed. I'm planning to hard code certain domain there and then add the rest of the url with url key.

<?php
/**
 * Featured Products Slider 
*/
?>
<?php 
$_productCollection = $this->getLoadedProductCollection(); ?>
<?php if ($_productCollection && ($_collectionSize = $this->getCollectionCount())): ?> 
<?php
$_helper = $this->getCatalogHelperOutput();
$theme = $this->getDataHelper();
$helpLabels = $this->getLabelHelper();
$helperImg = $this->getImageHelper();
$helperAddToLinks = $this->helper('Infortis\Base\Helper\AddToLinks');

$showCart = ($this->getHideButton()) ? false : true;
$imageTypeId = 'category_page_grid';
$showAltImage = $theme->getCfg('category/alt_image');

$sliderClasses = '';
$gridClasses = '';
$hash = $this->getFrontendHash();
$sliderId = "itemslider-featured-{$hash}";

//
// Slider configuration
// ----------------------------------------------

// Single item
if ($_collectionSize == 1)
{
    $sliderClasses .= ' single-item';
}

// Breakpoints
$breakpoints = $this->getBreakpoints();
if ($breakpoints === NULL)
{
    $breakpoints = '[0, 1], [320, 2], [480, 3], [768, 4], [992, 5], [1200, 6]';
}

// Responsive mode on/off and number of items
$isResponsive = $this->getIsResponsive();
if ($isResponsive === NULL)
{
    $isResponsive = true;
}

if (!$isResponsive)
{
    $showItems = $this->getShowItems();
    if (!$showItems)
    {
        $showItems = 5;
    }
}

// Timeout (automatic scrolling)
$timeout = $this->getTimeout();
if ($timeout === NULL)
{
    $timeout = intval($theme->getCfg('product_slider/timeout'));
}
else
{
    $timeout = intval($timeout);
}

// Number of items that should move on scroll
$move = $this->getMove();
if ($move === NULL)
{
    $move = 0;
}
else
{
    $move = intval($move);
}

// Loop
$loop = $this->getLoop();
if ($loop === NULL)
{
    $loop = $theme->getCfg('product_slider/loop');
}

// Speed (arrows / touch swipe)
$speed = intval($theme->getCfg('product_slider/speed'));

// Speed (automatic scrolling / pagination)
$autoSpeed = intval($theme->getCfg('product_slider/auto_speed'));

// Pause on mouse hover
$pause = $theme->getCfg('product_slider/pause');

// Lazy loading
$lazy = $theme->getCfg('product_slider/lazy');

// Pagination
$pagination = $this->getPagination();

//
// Grid configuration
// ----------------------------------------------

// Product image dimensions
$keepAspectRatio = $this->getData('keep_aspect_ratio');
if ($keepAspectRatio === NULL)
{
    $keepAspectRatio = $theme->getCfg('product_slider/keep_aspect_ratio');
}

// Image width
$imgWidth = $this->getData('img_width');
if ($imgWidth === NULL)
{
    // Default width has to be defined in the template to allow "Keep aspect ratio" option
    $imgWidth = 170;
}
else
{
    $imgWidth = intval($imgWidth);
}

// If keep aspect ratio, delete height
if ($keepAspectRatio)
{
    $imgHeight = null;
}
else
{
    $imgHeight = $imgWidth;
}

// If height parameter exists, it overrides current value of height
if ($this->getData('img_height') !== NULL)
{
    $imgHeight = intval($this->getData('img_height'));
}

// Size of item's elements
$size = $this->getSize();
if ($size)
{
    $gridClasses = ' ' . $size;
}
else
{
    if (isset($showItems))
    {
        if ($showItems >= 8)
        {
            $gridClasses = ' size-xs';
        }
        elseif ($showItems >= 6)
        {
            $gridClasses = ' size-s';
        }
    }
}

// Align elements to the center
if ($this->getCentered())
{
    $gridClasses .= ' centered';
}

// Equal height of items
if ($this->getData('equal_height'))
{
    $gridClasses .= ' equal-height';
}

?>
<div class="block itemslider<?php if($sliderClasses) echo $sliderClasses; ?> slider-arrows1 slider-arrows1-pos-top-right slider-pagination1">
<div class="block-title"><strong><?php echo $this->getBlockName(); ?></strong></div>
<div class="block-content">
    <div class="products-grid<?php if($gridClasses) echo $gridClasses; ?>">
        <div id="<?php echo $sliderId; ?>" class="products list items product-items">
            <?php foreach ($_productCollection as $_product): ?>
            <div class="item">
                <div class="product-item-info">
                    <div class="product-item-img" <?php /*style="max-width:<?php echo $imgWidth; ?>px;" */?> >

                        <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true); ?>" class="product-image">
3

Here is the method I used to get the product url.

It is definitely not optimal as I have to load the entire product to get it so very bad in terms of performance.

Create a block after that First you need to inject a Magento\Catalog\Model\ProductRepository in your constructor of your Block:

public function __construct(
   \Magento\Catalog\Model\ProductRepository $productRepository,
) {
  $this->_productRepository = $productRepository;
}

Then you load the product based on the product id:

public function getProductUrl($productId){
  $product = $this->_productRepository->getById($productId);
  return $product->getUrlModel()->getUrl($product);
}

Finally you can the URL model to retrieve the rewritten URL, Into you phtml file call like

echo  $this->getProductUrl($_product->getId());
  • 1
    Can confirm as working for Magento 2.2.3 – Joshua Flood Jun 3 '18 at 10:35
  • will do that asap. – Manish Jun 4 '18 at 9:51
  • Sorry I mean I tested already on 2.2.3 and it's still working. – Joshua Flood Jun 4 '18 at 11:20
  • 1
    No problem.. quite often I find what seems to be a perfect solution on this site and it is outdated, so figured it makes sense to add these comments until Magento 3 exists. – Joshua Flood Jun 4 '18 at 14:51
1

To get the url key you need to call UrlKey method as beleow

$_product->getUrlKey();

Hope this will help..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.