I generate/update several articles through a PHP script (in the cli folder) that parses an external data source (custom tables). This works well.
Now, if an article has not yet an image, the script must give it a random one.
foreach($arr_articles as $custom_id => $article_data)
{
// test if article exists
$sql = 'SELECT '.$db->quoteName('item_id')
.' FROM '.$db->quoteName($db_prefix.'fields_values')
.' WHERE '.$db->quoteName('field_id').' = 14 ' # my custom id
.' AND '.$db->quoteName('value').' = '.$db->quote($custom_id);
$db->setQuery($sql);
$article_id = $db->loadResult();
$jarticle = JTable::getInstance('content');
$article_has_image = False;
if(!is_null($article_id))
{
// article exists, load it
$jarticle->load($article_id);
// and look for its images
$images = json_decode($jarticle->images);
if(isset($images->image_fulltext) && !empty($images->image_fulltext))
{
$article_has_image = True;
}
}
if(! $article_has_image)
{
//set new one
$filepath = getRandomImage();
$jarticle->set('image_fulltext',$filepath);
}
//do more stuff, update custom fields...
//save
$jarticle->store();
}
getRandomImage()
gets an absolute filepath on the server.
My attempt with $jarticle->set('image_fulltext',$filepath);
does not seems to do anything, is there a better way to set the images (fulltext_image and intro_image) ?
if(isset($images->image_fulltext) && !empty($images->image_fulltext))
is a VERY common antipattern that shouldn't exist in anyone's applications. See more here: stackoverflow.com/a/4559976/2943403