Using the Joomla! 3.3 API to add articles programmatically

08.20.2014
#6980A3

Ever wanted to add articles to your Joomla! site from another source? If you've ever tried, you've probably run into a few issues—for example, articles that have been created directly in the database will not get indexed by the Smart Search component.

The main reason problems arise when adding articles directly to the database is the implementation of the assets table (used in Joomla! sites since 1.6). The assets table keeps a row for content items as it relates to Joomla!'s ACL system.

For simplicity's sake, just know that Joomla! relies a lot on the assets table and we'll need to make sure we add a row when adding an article programmatically.

Luckily, Joomla! makes it easy to import articles through the API.


Create an article object

First, let's create an object to store all of the article data:

$jarticle 				= new stdClass();
$jarticle->title			= 'New article added programmatically';
$jarticle->alias			= JFilterOutput::stringURLSafe( 'New article added programmatically' );

$jarticle->introtext			= '<p>Intro paragraph here</p>';

$jarticle->state			= 1;
$jarticle->catid			= 1;

$jarticle->created			= JFactory::getDate()->toSQL();
$jarticle->created_by			= JFactory::getUser()->id;

$jarticle->access			= 1;
$jarticle->metadata			= '{"page_title":"New article added programmatically","author":"Matthew Mesa","robots":""}';
$jarticle->language			= '*';

Get the content table, bind, check, and store

JTable is going to handle a ton of the legwork for you. All you'll need to do is create a new instance, bind the data, check it, and store it using the methods outlined below:

$table = JTable::getInstance('content', 'JTable');
$data = (array)$jarticle;

// Bind data
if (!$table->bind($data))
{
    //Handle the errors here however you like (log, display error message, etc.)
    return false;
}

// Check the data.
if (!$table->check())
{
    //Handle the errors here however you like (log, display error message, etc.)
    return false;
}

// Store the data.
if (!$table->store())
{
    //Handle the errors here however you like (log, display error message, etc.)
    return false;
}

For Joomla! 2.5 users

If you're using a previous version of Joomla!, refer to this version note in the Joomla! Documentation.