How to Programmatically Generate an SEF Link of a K2 Item

Although K2 is one of the most used and powerful Joomla extensions out there, there is very little documentation to do even the basic things with it. For example, how can one generate an SEF link to a K2 item based on the ID of that item?

That’s why, at itoctopus, we decided to share a little piece of code to generate a link to a K2 item simply based on its id. Here it is:

//we assume that the K2 ID is stored in the variable $k2Id
$db = JFactory::getDbo();
$sql = "SELECT alias, catid FROM #__k2_items WHERE id='".$k2Id."'";
$db->setQuery($sql);
$arrK2ItemInformation = $db->loadAssoc();

$sql = "SELECT alias FROM #__k2_categories WHERE id='".$arrK2ItemInformation['catid']."'";
$db->setQuery($sql);
$arrK2CategoryInformation = $db->loadAssoc();

require_once(JPATH_SITE.DS.'components'.DS.'com_k2'.DS.'helpers'.DS.'route.php');
$strK2SEFURL = JURI::root().JRoute::_(
K2HelperRoute::getItemRoute($k2Id.':'.urlencode($arrK2ItemInformation['alias']),
$arrK2ItemInformation['catid'].':'.urlencode($arrK2CategoryInformation['alias']
)));
$strK2SEFURL = str_replace('//', '/', $strK2SEFURL);
//the K2 SEF URL will be stored in $strK2SEFURL

You can put the above code in a template, a module, a component, or even a plugin, as long as you know the ID of the K2 item that you want to display the link for. It really works and it’s really that simple!

If the above code is a bit over your head, then fear not, just contact us and we’ll implement it for you. We won’t charge you much and we’ll do the work quickly, efficiently, and professionally!

No comments yet.

Leave a comment