02 Feb 2019

Conditional to find category of item outside of the K2 template files

Sometimes you need to know the category of the current K2 item, but reneder this information outside of the K2 template files. To check anything K2 outside of the K2 container, the code below is a good starting point.
By expanding this code a bit, you can check for all sorts of things, always from outside of the K2 container. For instance, I can use the following inside the <head> tags to trigger something specific to an item.

// Check if the item belongs to a specific category

// Gets component, view, and ID from the non-SEF URL
$whatComp = JFactory::getApplication()->input->get('option');
$whatView = JFactory::getApplication()->input->get('view');
$whatId = JFactory::getApplication()->input->get('id');
// Check if you are on K2 and viewing an item
if($whatComp == 'com_k2' && $whatView == "item") {
// Check the database for the category ID of the current K2 item
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->where($db->quoteName('id')." = ".$db->quote($whatId));
$myCatID = $db->loadResult();
// The number to be compared below is the ID of the category

if($myCatID == '17') {
// do something