How to make a URL SEF when triggered from Joomla backend?

Any Joomla developer worth his salt knows to use JRoute::_() to ensure he produces SEF URLs. This is an important SEO thing! However, if you’re writing code that does things from the Joomla Admin, the URLs turn out to be non-SEF. No I’m not talking about the URLs of the Joomla Admin itself.

For Instance,

Shika sends a notification email with a link to the course when a user enrolls for a course. When the user enrolls from the frontend, the email contains the shiny SEF URL. But if the admin enrolls the user, the email contains a non-SEF link in spite of correctly using JRoute::_() Don’t believe us ? Try for yourself :) Depending on the type of link you are creating the link might even have the part /administrator in it.

Seems dirty? Want to fix?

You just need the following piece of code to make an URL SEF even if triggered from backend.

$app = JFactory::getApplication();
// Here the contentURL is the url with correct itemid
$contentUrl = JRoute::_($contentUrl);

if ($app->isAdmin())
	$parsed_url = substr($contentUrl, strlen(JUri::base(true)) + 1);

	$appInstance = JApplication::getInstance('site');
	$router = $appInstance->getRouter();
	$uri = $router->build($parsed_url);
	$parsed_url = $uri->toString();
	$contentRoutedUrl = substr($parsed_url, strlen(JUri::base(true)) + 1);

The $contentRoutedUrl is the SEF URL.

I’m sure this will help many a lost Joomla programmers tame their admin-produced links.

Do you have any such tricks or gotchas that you’ve seen or fixed before? We’d love to hear those in the comments!