Saturday, June 18, 2011

Joomla Article Dynamic Content: Quick Hack

After searching around for a little while to find a way to easily add custom PHP into Joomla articles as main content, so that main articles could have dynamic content, I came up dry.

I am a huge fan of the PHP Modules extension (Fiji Web Design), but it only allows you to define modules with arbitrary PHP, they will not let me dynamically alter the content of an article based on things like the contents of a database, or a special query string sent with the page URL, or anything like that.

So, I had to come up with a hack on my own.

These are the steps I took:

  1. Create the article that you want to have dynamic content on. Anything that will be displayed the same all the time, you can enter as normal article text. Any blocks or sections that you want to change dynamically, based on the contents of a database table or whatever, simply put in some kind of special keyword text. So it will look something like this:
    The most recently created items in our database are:
    {{PHP-RECENT-LIST}}
    Check them out!
    Save your article so that it looks just like that
  2. In your installation of Joomla, find the script that actually renders the views of article pages. Usually, this will be found in the folder /components/com_content/views/article in a file called view.html.php
  3. In this file, there is a function called "display". Somewhere appropriately near the end of this function, insert your code that will replace your custom text label with the HTML that you want

How do you replace the text? The body of the article is stored in a variable called $item->text. So you can simply create a code-block that looks something like this inside the function:

if (strpos($item->text,'{{PHP-RECENT-LIST}}')) {

  $html = '';
  $database =& JFactory::getDBO();
  $query = (query that gets the stuff you need);
  $database->setQuery( $query );
  $rows = $database->loadObjectList();
  foreach($rows as $row){
    $html .= (stuff);
  }
  $item->text = str_replace('{{PHP-RECENT-LIST}}', $html, $item->text); 
}

Now, I know this is a total hack. (At least in the sense that it requires you to modify code that comes with the core Joomla package.) I'm sure there is a more elegant or object-oriented or exensible or modular or otherwise modern-and-or-cool way of doing this. But this is quick and it works. Just make sure you keep these modifications together and well-commented so you don't have trouble hunting them down later when you want to change them

No comments:

Post a Comment