PHP Joomla! 6 Joomla! 5 Joomla! 3 (Legacy) Plugin Intermediate

Parse Custom Shortcodes Inside onContentPrepare

Replaces {mywidget id=12} tokens inside articles using typed ContentPrepareEvent and a fast str_contains guard.

Updated on 24 November 2026 44 copies 160 views
plugins/content/example/src/Extension/Example.php
<?php

declare(strict_types=1);

use Joomla\CMS\Event\Content\ContentPrepareEvent;

public function onContentPrepare(ContentPrepareEvent $event): void
{
    $context = $event->getContext();
    if ($context === 'com_finder.indexer') {
        return;
    }

    $article = $event->getItem();
    if (!isset($article->text) || !str_contains((string) $article->text, '{meuwidget')) {
        return;
    }

    $article->text = preg_replace_callback(
        '/\{meuwidget\s+id=(\d+)\}/i',
        static fn (array $m): string => '<div class="widget-box">ID ' . (int) $m[1] . '</div>',
        (string) $article->text
    );
}
Uses strongly typed ContentPrepareEvent for Joomla 5 and 6 SubscriberInterface plugins.
plugins/content/example/src/Extension/Example.php
<?php
public function onContentPrepare($context, &$article, &$params, $page = 0)
{
    if (strpos($article->text, '{meuwidget') === false) {
        return true;
    }
    $article->text = preg_replace('/\{meuwidget\s+id=(\d+)\}/i', '<div class="widget-box">ID $1</div>', $article->text);
    return true;
}
Classic Joomla 3 onContentPrepare signature.

Technical explanation and best practices

Always short-circuit early with str_contains($article->text, '{mywidget') before running regular expressions so pages without shortcodes pay near-zero overhead.

Direct Engineering

Have a Joomla project or technical challenge in mind?

From architectural diagnosis to production deployment, directly with the engineer.