0

I am trying to display a category name in a module position.

I tried:

<?php echo $listing['Category']['title'];?>

It did not work.

I followed this link, but it shows the article title and I need the category one. I'm working on Joomla 1.7.

brasofilo
  • 25,496
  • 15
  • 91
  • 179
user1154641
  • 5
  • 1
  • 1
  • 7
  • 1
    got the answer. though sombody might benefit from it being here. setQuery('SELECT #__categories.title FROM #__content, #__categories WHERE #__content.catid = #__categories.id AND #__content.id = '.$id); $category = $db->loadResult(); echo $category; ?> cheers – user1154641 Jan 19 '12 at 15:56
  • Hi user1154641, Please post the above as an answer and mark it as solved. So that other needful people can spot it easily. :) – saji89 Jan 20 '12 at 04:46

3 Answers3

6

Much more simple answer:

<?php echo $this->escape($this->item->category_title);?>
Semmerket
  • 73
  • 1
  • 5
5

As per the posters comment in the OP:

<?php 
    $db = &JFactory::getDBO(); 
    $id = JRequest::getString('id'); 
    $db->setQuery('SELECT #__categories.title FROM #__content, #__categories WHERE #__content.catid = #__categories.id AND #__content.id = '.$id); 
    $category = $db->loadResult();
    echo $category; 
?>
travega
  • 8,284
  • 16
  • 63
  • 91
5

Travega is really close, his code works on pages, but not on category pages.

When you use $id = JRequest::getString('id'); on a category page (such as a category blog or list page) the id of the category is returned. This means we need more context of the id variable, in this case the 'view'.

Here is my modified version of travega's code:


function getCategoryName() {
    //Modified from: http://stackoverflow.com/questions/8928967/joomla-display-catagory-name-in-template

    $db = &JFactory::getDBO(); 
    $id = JRequest::getString('id'); 
    $view = JRequest::getString('view'); 

    if ($view == 'category') {
        $sql = "SELECT title FROM #__categories WHERE #__categories.id = $id";
    } else {
        $sql = "SELECT #__categories.title FROM #__content, #__categories WHERE #__content.catid = #__categories.id AND #__content.id = $id";
    }

    $db->setQuery($sql); 
    $category = $db->loadResult(); 
    return $category; 
}

Other relevant info:

I've only tested this on Joomla 2.5.3 on cat blog and cat list pages. I've not tested it on anything other than com_content component. This means it probably won't work on weblink, contact, etc pages as you may again loose the context.

Nick Yeoman
  • 51
  • 1
  • 2