Programmatically set article image

by nicolallias   Last Updated September 04, 2019 11:10 AM

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) ?



Related Questions


Add html to Article Image captions

Updated November 08, 2017 16:10 PM

Additional "Images And Links" fields - corect way

Updated January 26, 2018 11:10 AM

Edit multiple images at once

Updated March 23, 2016 08:04 AM

Random image in an article

Updated April 22, 2016 09:04 AM