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!

0

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.

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.