Joomla: dynamically adding stylesheets by category and section

I once had the misfortune of developing a Joomla site with three separate templates, each of which contained four separate color schemes. The color scheme needed to be selected based on the content's section and/or category.

This PHP script will cycle through various methods for determining category id, section id, or content id. It also includes an array for manually setting the stylesheet by id.

//get article id

//look for article id in get variable id

if (array_key_exists('id', $_GET)){
$articleID = $_GET['id'];
}
else {
$articleID = $_GET['catid'];
}
//if article id is concatenated, strip extra characters
if ( strpos($articleID, ':') > 0 ) {
$articleID = substr($articleID, 0, strpos($articleID, ':'));
//$articleID = preg_replace('/[^0-9]/', '', $articleID);
}

else {
$Itemid = $_GET['Itemid'];
}

//find section and category ids
if ($articleID != ''){
$query = 'SELECT s.title as sectiontitle FROM #__categories as cat, #__sections as s WHERE cat.id = ' . $articleID . ' AND cat.section = s.id';
$db =& JFactory::getDBO();
$db->setQuery($query);
$dbResult = $db->loadAssoc();
$sectionTitle = $dbResult['sectiontitle'];
}

if (!isset($sectionTitle)){
$query = 'SELECT s.title as sectiontitle, cat.title as cattitle FROM #__categories AS cat, #__content as c, #__sections as s WHERE c.id = ' . $articleID . ' AND c.catid = cat.id AND c.sectionid = s.id';
$db =& JFactory::getDBO();
$db->setQuery($query);
$dbResult = $db->loadAssoc();

$sectionTitle = $dbResult['sectiontitle'];
$categoryTitle = $dbResult['cattitle'];
}

//load section-specific css file to set color scheme
if ($sectionTitle != ''){

switch ($sectionTitle) {
case 'Section 1':
$stylesheet = 'blue';
break;

case 'Section 2':
$stylesheet = 'purple';
break;

case 'Section 3':
$stylesheet = 'green';
break;

case 'Section 4':
$stylesheet = 'brown';
break;

}

}
else {
//override default settings for specific pieces of content
$content_ids = array(
114 => 'blue',
149 => 'purple',
150 => 'green',
151 => 'brown'
);
foreach ($content_ids as $id => $scheme){
if ($Itemid == $id){
$stylesheet = $scheme;
$match = TRUE;
}
}

if ($match == FALSE){
$stylesheet = 'default';
}

}

$stylesheet .= '.css';
$css_link = '
';

echo $css_link;
/*
echo "

\n";
echo "

\n";
echo "

\n";
echo "

\n";
echo "

\n";
echo "

\n";
*/
?>

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.