K2 Templating: Cheating the MVC with JFactory:getDBO()

Unfotunately, not everything is thought out in K2.  There really isn’t a way to get a list of tags for the current category you’re in.  BUT, there’s a way when there’s a will…..

In this tutorial we show you how to access the Joomla Database using JFactory:getDBO().  Our specific example works on retrieving specific tags associated with a K2 category.

Sometimes, you have to play dirty by using JFactory:getDBO().  Someone commented on one of our blog/tutorial entries that they wanted tag filtering based on the category that they were in. So did we when we rebuilt our site in January….. We didn’t want to share this code since we think its kind of a dirty little hack. That said something like this can be used:

$dbtag = JFactory::getDBO();
$query = "
SELECT DISTINCT tags.name AS name
FROM #__k2_tags AS tags
LEFT JOIN #__k2_tags_xref xref ON xref.tagID = tags.id
LEFT JOIN #__k2_items items ON items.id = xref.itemID
WHERE items.catid = ".intval($this->category->id)."
ORDER BY tags.name ASC

$tags = $dbtag->loadObjectList();

Above is the database code that pulls all the tags for the child item (this isn’t a complete solution if you have nested categories). We’re not proud of calling JFactory::getDBO() from a View file (totally breaks MVC rules), but since we didn’t have another way we had to do it. I guess its better than WordPress templates that do this at every opportunity.

Below is the display code for the tags:

<?php foreach($tags as $tag):?>
<a class="<?php echo str_replace(' ','-',$tag->name) ?>"><?php echo $tag->name;?></a>
<?php endforeach;?>


We didn’t need to link to tags ourselves so we didn’t have to worry about creating tag links.  If you really need that feature, I guess you can look it up in the K2 source!  Good luck!