How to Create an Article in Joomla with PHP

Below, you can find a PHP snippet that allows you to create a new article by providing a title, alias, intro, full text, and the category and its state.

Joomla 4+

$app = \Joomla\CMS\Factory::getApplication();
$mvcFactory = $app->bootComponent('com_content')->getMVCFactory();
$articleModel = $mvcFactory->createModel('Article', 'Administrator', ['ignore_request' => true]);

$article = [
    'catid' => 2,
    'alias' => \Joomla\CMS\Filter\OutputFilter::stringURLSafe('A41234My Article Title'),
    'title' => '123My Article Title',
    'introtext' => 'My Article Intro Text',
    'fulltext' => 'My Article Full Text',
    'state' => 1,
	'language' => '*',
];

if (!$articleModel->save($article))
{
    throw new Exception($articleModel->getError());
}

Joomla 3

JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_content/tables');

$table = JTable::getInstance('Content', 'JTable', array());

$data = [
    'catid' => 1,
    'alias' => JFilterOutput::stringURLSafe('My Article Title'),
    'title' => 'My Article Title',
    'introtext' => 'My Article Intro Text',
    'fulltext' => 'My Article Full Text',
    'state' => 1,
];

// Bind data
if (!$table->bind($data))
{
    throw new Exception($table->getError());
}

// Save Article
if (!$table->store())
{
    throw new Exception($table->getError());
}
Last updated on Nov 28th 2024 09:11