RocketTheme Blog

Simple CSS Style Plugin for Joomla

When I was writing the previous blog post about Mac applications I had a need to add some custom <style> elements to provide the layout that I wanted. Now it's quite common for people to just input some tags in their content but don't do it! It might 'work' but it's not valid XHTML. All style declarations should be in the <head> element of your page. Unfortunately it's not very easy to add style declarations here when you only need them for one page. Traditionally you would have to edit your template CSS file and add the elements there. It's a hassle and also it means those styles are going to be in the CSS for every page of your site, if you need them or not.

I decided to whip up a quick content plugin to take care of this issue once and for all. What it does, is find style elements between {rokstyle}{/rokstyle} plugin tags, and then puts those elements into the <head>tag using the JDocument object and theaddStyleDeclaration method. The code is very simple and here it is:

<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

$mainframe->registerEvent( 'onPrepareContent', 'plgContentRokStyle' );

function plgContentRokStyle( &$row, &$params, $page=0 )
{
$display = true;

//simple performance check to determine whether bot should process further
if ( strpos( $row->text, '{rokstyle}' ) === false) {
return true;
}

//put this on your page if you want rokstyle plugin to not run on this article
if (strpos ( $row->text, '<!--rokstyle-->') !== false) { 
return true;
}

// Get plugin info
$plugin =& JPluginHelper::getPlugin('content', 'rokstyle');


$pluginParams = new JParameter( $plugin->params );

// define the regular expression for the bot
$regex = "#{rokstyle}(.*?){/rokstyle}#s";

// check whether plugin has been unpublished
if ( !$pluginParams->get( 'enabled', 1 ) ) {
$row->text = preg_replace( $regex, '', $row->text );
return true;
}

$row->text = preg_replace_callback( $regex, 'plgContentProcessRokStyle', $row->text );

return true;
}

function plgContentProcessRokStyle(&$matches) {

$text = $matches[1];

$doc = & JFactory::getDocument();
$doc->addStyleDeclaration($text);

return "";
}

?>

An example of how you would use this would be to put this at the top of your article that needed the custom style:

{rokstyle}
.appblock-title {font-size:250%;line-height:150%;color:#000;margin:40px 0 20px;border-bottom:1px solid #e7e7e7;}
.appblock {overflow:auto;margin-top:15px;}
.appblock img {float:left;margin-top:15px;}
.appblock h2 {color:#666;}
.appblock h4, .appblock p {margin-left:120px;}
{/rokstyle}

You can download the finished plugin here.

Member Login: