Get first image from article content, in Joomla4

66 views
Skip to first unread message

Sociedad Civil Cuba

unread,
Feb 6, 2023, 8:20:53 PM2/6/23
to Joomla! General Development
Hi, this is my first try with J4. I just want, given an article (by its ID), if such article has no featured image, to grab the first image from their content, and use as a kind of featured image. There is any plugin that currently do that? Or anyone can share a code (at least to get the content given the ID of the article)? Thanks in advance.

Viper

unread,
Feb 7, 2023, 1:26:06 PM2/7/23
to Joomla! General Development
public function getArticleById(int $id)
{
    /** @var \Joomla\Database\DatabaseDriver $db */
    $db = Factory::getContainer()->get('DatabaseDriver');

    $query = $db->getQuery(true)
        ->select('*')
        ->from($db->quoteName('#__content'))
        ->where($db->quoteName('id') . ' = :id')
        ->bind(':id', $id, \Joomla\Database\ParameterType::INTEGER);

    try
    {
        $db->setQuery($query);

        return $db->loadObject();
    }
    catch (\RuntimeException $e)
    {
        return false;
    }
}

will return an object with all article fields.

Wen somewhere do checks for images...

$id = 99;
$data = $this->getArticleById($id);
$images = json_decode($data->images, true);
$introImage = count($images) ? $images['image_intro'] : '';

if (!empty( $introImage))
{
   // Image found, do something

Peter Tuson

unread,
Feb 7, 2023, 1:45:37 PM2/7/23
to Joomla! General Development
Hello Viper.

In our system, if the image is in the intro text it is as <p><img ... \></p>

We use this code for dealing with it in one of our own Joomla 4 modules

            if (preg_match_all("/<p.+<\/p>/", $item->introtext, $matches)) {
                foreach ($matches[0] as $match) {
                    if (strpos($match, 'img') !== false) {
                        $r['img']   = str_replace('images', 'https://www.eluceoeducation.org/images', $match);
                    } else if (strpos($match, 'hidden') == false) {
                        $r['text'] .= strip_tags($match, '<p>');
                    }
                }
            }

We only expect the first image in the introtext.

Hope this helps.

Regards,

Peter.
Reply all
Reply to author
Forward
0 new messages