How to add a css StyleSheet to a Joomla 2.5 content plugin

In our Hello World Joomla 2.5 content plugin, we only had the most necessary files – helloworld.php, helloworld.xml, and index.html. If you want to include css files within your plugin, you can easily do that using the addStyleSheet function. In this tutorial, we’ll show you how to add css stylesheet files to your plugin.

How to add a css StyleSheet to a Joomla 2.5 content plugin

Step 1: Create the CSS Stylesheet

The first thing to do is to actually create the css stylesheet. In our example, we created a css file named mystyle.css

Step 2: Reference your css file in your XML file

After you’ve created your css file, you need to update your plugin’s XML file to include the css file. In our example, we need to add mystyle.css to our helloworld.xml file. Here is the section of code we used to accomplish this:

<files>
<filename plugin="helloworld">helloworld.php</filename>
<filename>index.html</filename>
<filename>mystyle.css</filename>
</files>

In this example, we used <filename> to include mystyle.css.


Step 3: Load the stylesheet using addStyleSheet

The last thing we need to do is load the stylesheet using addStyleSheet. We can do this within the onContentPrepare function, as in:

public function onContentPrepare($context, &$row, &$params, $page = 0)
{
$document = & JFactory::getDocument();
$document->addStyleSheet(JURI::base(). "plugins/content/helloworld/mystyle.css");
}

As you can see, we first declared $document, and then we used the $document->addStyleSheet to add the URL of the stylesheet to the document. As this css file is now included within the plugin, we can get the absolute URL of the plugin using a combination of JURI::base() along with the path to the file starting with plugins/content.

The above lines of code add the following reference in the head of our Joomla 2.5 page:

<link rel="stylesheet" href="http://YourDomain.com/plugins/content/helloworld/mystyle.css" type="text/css" />

If you have any trouble with adding css files to a Joomla 2.5 plugin, post a question in the comments at the bottom of this page and we’ll more than happy to help!

Be Sociable, Share!

Leave a comment