2

I have a custom category indexer which grabs Magento categories and index them to a search service. Within each category I need to index it's URL which I do by code

$url = $category->getUrl();

where $category is instance of Magento\Catalog\Model\Category.

The issue is when the store is set to use Secure URLs in front end. Then this code always return the not-secure URL. Do you know how to get the secure one?

With product I solved it with code

$url = $product->getUrlModel()->getUrl($product, ['_secure' => true]);

because simple $url = $product->getProductUrl(); returned a not-secure URL as well.

However from Category I don't have access to any UrlModel or any way how to pass _secure parameter to getUrl() method.

My current configuration: enter image description here

Thanks for any help!

Himanshu
1,76618 silver badges34 bronze badges
asked Mar 9, 2017 at 15:37

2 Answers 2

1

Finally I "hacked" it by getting UrlInstance from Category object, getting secure and non-secure base URLs and replacing it according front-end setting:

private function getUrl(Category $category)
{
 $categoryUrl = $category->getUrl();
 if ($this->config->useSecureUrlsInFrontend($category->getStoreId()) === false) {
 return $categoryUrl;
 }
 $unsecureBaseUrl = $category->getUrlInstance()->getBaseUrl(['_secure' => false]);
 $secureBaseUrl = $category->getUrlInstance()->getBaseUrl(['_secure' => true]);
 if (strpos($categoryUrl, $unsecureBaseUrl) === 0) {
 return substr_replace($categoryUrl, $secureBaseUrl, 0, mb_strlen($unsecureBaseUrl));
 }
 return $categoryUrl;
}

So far it works fine.

If you have more elegant (less hacky) solution, please post it here. I'm happy to change the correct answer.

answered Mar 10, 2017 at 12:19
0

I used Jan's idea. But I had to get the secue_base_url for the store using storeManagerInterface. So I did something like this:

// using \Magento\Store\Model\StoreManagerInterface storeManagerInterface
public function getCategoryUrl($category) {
 $categoryUrl = $category->getUrl();
 $unSecureBaseUrl = $this->storeManagerInterface->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB, false);
 if (strpos($categoryUrl, $unSecureBaseUrl) === 0) {
 $secureBaseUrl = $this->storeManagerInterface->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB, true);
 $categoryUrl = substr_replace($categoryUrl, $secureBaseUrl, 0, strlen($unSecureBaseUrl));
 }
 return $categoryUrl;
}
answered Aug 3, 2020 at 16:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.