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!

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.

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;
}

Your Answer

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

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