Make changes to an article automatically using a plugin

From Joomla! Documentation

Overview[edit]

Plugins are the simplest extensions to write. A simple plugin requires only two files. Yet plugins can be extremely handy.

One common case for using plugins is doing some customized processing every time an article is saved. For example:

  • Change the published state of an article.
  • Add standard text to articles.
  • Set the Section or Category for an article.

Let's see how you can use a simple plugin to do these tasks.

First Plugin[edit]

A simple plugin has two files. One is an XML file that tells Joomla! how to install the plugin. The other is the actual plugin PHP code.

To make it as easy as possible for people to write plugins, Joomla! includes example plugins in every installation. In our example, we are writing a content plugin, since we are working with articles. The two example files we can use as guidelines are plugins/content/example.xml and plugins/content/example.php.

The XML file for our example is called modifyarticle.xml. We just copied the file plugins/content/example.xml to modifyarticle.xml and put it in a new folder outside of the Joomla! installation. (We will use the Joomla! install program later on to add this to our Joomla! system. For now we want to keep this separate from Joomla!.) Then we edited it:

<?xml version="1.0" encoding="utf-8"?>
<install version="1.5" type="plugin" group="content">
<name>Modify Edited Articles</name>
<creationDate>January 2009</creationDate>
<author>Joomla Doc Team</author>
<authorEmail>myemail@myemail.com</authorEmail>
<authorUrl>http://joomlacode.org</authorUrl>
<copyright>Copyright (c) 2009</copyright>
<license>GPL</license>
<version>1.0.0</version>
<description>Example plugin for Joomla! wiki.</description>
<files>
   <filename plugin="modifyarticle">modifyarticle.php</filename>
</files>
</install>

Next, we copy the file plugins/content/example.php to modifyarticle.php and put it in the same folder outside of the Joomla! installation. Then we edit this file so it reads:

<?php
/**
 * @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 */

// Check to ensure this file is included in Joomla!
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

class plgContentModifyArticle extends JPlugin
{

	/**
	 * Example before save content method
	 *
	 * Method is called right before content is saved into the database.
	 * Article object is passed by reference, so any changes will be saved!
	 * NOTE:  Returning false will abort the save with an error.
	 * 	You can set the error by calling $article->setError($message)
	 *
	 * @param 	object		A JTableContent object
	 * @param 	bool		If the content is just about to be created
	 * @return	bool		If false, abort the save
	 */
	function onContentBeforeSave( $context, &$article, $isNew )
	{
		$user =& JFactory::getUser(); // get the user
		if ($user->usertype == 'Author') { // unpublish if user is "Author"
			$article->state = 0; // from dev 11:59
		}
		return true;
	}
}

Notice that the example.php file has six methods plus the constructor. These document the six possible events that you can use for plugins. In our example, we want to modify the article just before it is saved to the database. We call our method (or function) onContentBeforeSave. This method name must be exactly as shown. The name is what tells Joomla! when to run our plugin.

In standard Joomla!, when a user in the Author group first submits a new article, it is set to Unpublished. However, once the article has been published, this user can edit the article and it stays published. In our example, we want to change this so that, each time an article is edited by a user in the Author group, it gets changed back to Unpublished.

The code above does that. First, we get the user. Then, if the user is in the Author group, we change the article's state to zero, meaning Unpublished. Notice that the method has $article as a parameter, so its fields and methods are all available to us.

Install the Plugin[edit]

Once we have the plugin coded, we need to create a zip archive so we can install it in our Joomla! site. Here are the steps:

  • Use any Zip or Gzip program to make a Zip or Gzip archive of the two files created above.
  • In the back end of your Joomla! site, navigate to Extensions  Install/Uninstall.
  • Press Browse and find your zip archive file.
  • Press Upload File and Install. You should get a message indicating that the extension was installed successfully.
  • Finally, navigate to Extensions  Plugin Manager, find the new plugin (called Modify Edited Articles based on the name in the XML file), and enable it.

At this point, you should be able to test that it is working as expected.

Add Standard Text[edit]

Once we have the basic framework, changing the plugin to do other things is simple. For example, say we want to add standard text to any article submitted by a user in the Author group. Here is the code for the onBeforeContentSave() method:

	function onContentBeforeSave( $context, &$article, $isNew )
	{
		$newText = '<p>This is my new text to add to the article.</p>';
		$user =& JFactory::getUser(); // get the user
		if ($user->usertype == 'Author') {
			if ($article->fulltext) {
				if (strpos($article->fulltext, $newText) == 0) {
					$article->fulltext .= $newText;
				}
			}
			else {
				if (strpos($article->introtext, $newText) == 0) {
					$article->introtext .= $newText;
				}
			}
		}
		return true;
	}

In this code, we have some standard text we put in the $newText variable. Then we deal with a complication of the $article object. Joomla! articles can have an optional Read more... break. If they don't have one, the entire text of the article is in the introtext field. If there is a Read more... break, then the part of the article after the break is in the fulltext field.

So, in the code, we have to handle both cases. If there is something in fulltext, we add the standard text there. Otherwise, we add it to introtext.

There is one other complication. We don't want to add the standard text if it already there. Otherwise, we would keep adding more copies of it each time the article is edited. We test to see if it already part of the article's text and we only add it if it isn't already there.

Notice that the second parameter of this method is $isNew. This is a Boolean that is true if this is a new article. We could test for that if we only wanted to add the text for new article submissions.

Set the Section or Category[edit]

Setting the Section or Category ID of an article is easy. For example, in the Sample Website, this code

   $article->sectionid = '4';
   $article->catid = '25';

would change the article's Section to About Joomla! and Category to The Project. Note that you need to use the id fields for the Section and Category. In this example, you also might want to remove these fields from the Frontend form (by using a template override).

Other Things We Can Do[edit]

It is useful to understand that any of the article's fields are available here. Here is a partial list:

  • title: article's title
  • alias: article's alias
  • state: 0 for unpublished, 1 for published, -1 for archived
  • created: date created
  • created_by: user id of author
  • created_by_alias: author alias field
  • modified: date last modified
  • modified_by: user id of last author to modify
  • metakey: Metadata Information / Keywords
  • metadesc: Metadata Information / Description
  • access: 0 for public, 1 for registered, 2 for special

Also, there are other built-in events we can use for plugins, see Plugin Events Content documentation for more info. These are documented in the plugins/content/example.php file. In addition, there are other plugin types. See the plugins section of the Wiki for more information.