Auto-Generate Meta Descriptions from Article Text in Joomla

Give every Joomla article its own meta description, written from its text automatically, so your pages stand out in search, using one PHP snippet.

Auto-Generate Meta Descriptions from Article Text in Joomla
Heads up! This article contains PHP code and is intended for developers. We offer this code as a courtesy, but don't provide support for code customizations or 3rd party development.

Every Joomla article has a Meta Description field, and on most sites it sits empty. Leave it empty and Joomla falls back to your site-wide description, so hundreds of articles share one line of text, or have none at all.

Articles opened from a category blog get it worse: they all show the blog menu item's description. You can give every article its own description, built from its first few lines, with one PHP snippet in Code Snippets.

The PHP snippet code

On every article page, the snippet checks whether the article has a description. If it doesn't, it takes the opening text of the article, without headings, scripts or plugin tags like {loadmodule}, cuts it at the last whole word under 155 characters, and uses that.

use Joomla\CMS\Document\HtmlDocument;
use Joomla\CMS\Factory;
use Joomla\Database\DatabaseInterface;
use Joomla\Database\ParameterType;
use Joomla\String\StringHelper;

// Maximum length of the description. Google cuts most snippets at around 155.
$maxLength = 155;

// Do not edit below.

$app = Factory::getApplication();

$app->registerEvent('onBeforeCompileHead', function () use ($app, $maxLength)
{
    $document = $app->getDocument();
    $input    = $app->getInput();
    $id       = $input->getInt('id');

    // Run on single article pages only.
    $isArticle = $input->getCmd('option') === 'com_content'
        && $input->getCmd('view') === 'article';

    if (!($document instanceof HtmlDocument) || !$isArticle || !$id)
    {
        return;
    }

    $db    = Factory::getContainer()->get(DatabaseInterface::class);
    $query = $db->createQuery()
        ->select($db->quoteName(['introtext', 'fulltext', 'metadesc']))
        ->from($db->quoteName('#__content'))
        ->where($db->quoteName('id') . ' = :id')
        ->bind(':id', $id, ParameterType::INTEGER);

    $article = $db->setQuery($query)->loadObject();

    // Keep the description you wrote in the article's Publishing tab.
    if (!$article || trim($article->metadesc) !== '')
    {
        return;
    }

    // Keep the description of a menu item that links to this exact article.
    $menu = $app->getMenu()->getActive();

    if ($menu
        && ($menu->query['view'] ?? '') === 'article'
        && (int) ($menu->query['id'] ?? 0) === $id
        && trim((string) $menu->getParams()->get('menu-meta_description')) !== '')
    {
        return;
    }

    // Turn the article into plain text, without headings, scripts or {plugin} tags.
    $text = $article->introtext . ' ' . $article->fulltext;
    $text = preg_replace('#<(h[1-6]|script|style)\b[^>]*>.*?</\1>#is', ' ', $text);
    $text = preg_replace('#\{[^{}]*\}#', ' ', $text);
    $text = strip_tags(str_replace('<', ' <', $text));
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $text = trim(preg_replace('#[\s\x{00A0}]+#u', ' ', $text));

    if ($text === '')
    {
        return;
    }

    // Cut at the last whole word that fits.
    if (StringHelper::strlen($text) > $maxLength)
    {
        $text  = StringHelper::substr($text, 0, $maxLength - 3);
        $space = StringHelper::strrpos($text, ' ');
        $text  = $space ? StringHelper::substr($text, 0, $space) : $text;
        $text  = rtrim($text, ' ,.;:-') . '...';
    }

    $document->setDescription($text);
});

A description you type into an article always wins, so you can still write one by hand for your most important pages. The same goes for a menu item that links to a single article and has its own description. Articles opened from a category blog get their own description instead of the blog's.

The snippet only changes the page Joomla sends to the browser. Your articles stay as they are, and unpublishing the snippet brings back the old descriptions.

How to add this snippet

  1. Install Code Snippets if it isn't installed already.
  2. Log into your Joomla backend.
  3. Go to Components → Tassos Code Snippets.
  4. Click New.
  5. Enter a title, for example Auto meta descriptions.
  6. Set Code Type to PHP.
  7. Set Insertion Method to Auto-Insert Locations.
  8. Set Location to On Page Load.
  9. Paste the code above into the editor.
  10. Click Save & Close.

Check that it works

  1. Open an article with an empty Meta Description field and view the page source.
  2. Look for this line in the <head>:
<meta name="description" content="The first sentences of your article...">

Then open an article where you wrote a description. It should still show yours. Google picks up the new descriptions the next time it crawls each page.

If the description looks wrong

  • The page still shows the old description. Clear the Joomla cache (System → Clear Cache) and any page cache your host adds, then reload.
  • The description starts with an image caption or a "Written by" line. That's the first text in the article body. Move it below the first paragraph, or write a description for that article by hand.
  • Another SEO extension also sets descriptions. Only one of them should write the tag. Turn off the description feature in that extension, or unpublish the snippet.

To keep thin pages out of Google, see Add Noindex to Specific Pages in Joomla. To learn more about how PHP snippets work, read the PHP snippet docs.

Last updated on Oct 15th 2026 14:10