Building a Sentiment Analysis Plugin in Joomla Using PHP and OpenAI API

PHP CMS Frameworks November 03, 2025

Joomla's content plugin system is underused. Most developers reach for components when a simple content plugin hooked into onContentBeforeSave would do the job in a fraction of the code.

This tutorial is a good example of that. The idea is simple: every time an article is saved, we send the text to OpenAI and get back one word, positive, negative, or neutral.

That result gets appended to the meta keywords field and flashed as an admin message. Nothing fancy, but on a community site or news portal where editors are processing dozens of submissions a day, having that sentiment label right in the save workflow saves real time.

Two files, no Composer, no service container. Just a manifest XML and a single PHP class extending CMSPlugin.

What You’ll Need

Before we start, make sure you have:

  • Joomla 5.x installed
  • PHP 8.1 or newer
  • cURL enabled on your server
  • An OpenAI API key

Once that’s ready, let’s code.

Step 1: Creation of the Plugin

In your Joomala system, make a new folder within the system under the name of the plugin:

/plugins/content/aisentiment/

Thereupon in that folder generate two files:

  • aisentiment.php
  • aisentiment.xml

aisentiment.xml

This is the manifest file that the Joomla plugin identifies the identity of this particular plugin and the files that should be loaded into it.

<?xml version="1.0" encoding="utf-8"?>

<extension type="plugin" version="5.0" group="content" method="upgrade">

    <name>plg_content_aisentiment</name>

    <author>PHP CMS Framework</author>

    <version>1.0.0</version>

    <description>Analyze sentiment of comments or articles using OpenAI API.</description>

    <files>

        <filename plugin="aisentiment">aisentiment.php</filename>

    </files>

</extension>


Step 2: Add the PHP Logic

Now let’s write the plugin code.

aisentiment.php

<?php
defined('_JEXEC') or die;

use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;

class PlgContentAisentiment extends CMSPlugin
{
    private $apiKey = 'YOUR_OPENAI_API_KEY';
    private $endpoint = 'https://api.openai.com/v1/chat/completions';

    public function onContentBeforeSave($context, $table, $isNew, $data)
    {
        // Only process if content exists
        if (empty($data['introtext']) && empty($data['fulltext'])) {
            return true;
        }

        $text = strip_tags($data['introtext'] ?? $data['fulltext']);
        $sentiment = $this->getSentiment($text);

        if ($sentiment) {
            $data['metakey'] .= ' Sentiment:' . ucfirst($sentiment);
            Factory::getApplication()->enqueueMessage("AI Sentiment: {$sentiment}", 'message');
        }

        return true;
    }

    private function getSentiment($text)
    {
        $payload = [
            "model" => "gpt-4o-mini",
            "messages" => [
                ["role" => "system", "content" => "You are a sentiment analysis model. Return only one word: positive, negative, or neutral."],
                ["role" => "user", "content" => $text]
            ]
        ];

        $ch = curl_init($this->endpoint);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "Authorization: Bearer {$this->apiKey}"
            ],
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_TIMEOUT => 15
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);
        return strtolower(trim($data['choices'][0]['message']['content'] ?? 'neutral'));
    }
}

This extension will be installed on Joomla and will work together with the content workflow (onContentBeforeSave) and send the content of the article to the OpenAI API. This model examines the tone and produces one of three values, including positive, negative, and neutral.

The output is presented in the administration of Joomla as an output when the article is saved.


Step 3:Install and activate the Plugin.

Zip the folder (aisentiment) of the compressor: aisentiment.zip

Within Joomla administration log, go to: System → Extensions → Install

Upload the zip file.

Once installed, visit System -> Plugins where you will find the AI Sentiment one and turn it on.


Step 4: Test It

Open an existing article, or create one.

Enter some text — for example:

This product is out of my expectations and it works excellently!

Click Save.

Joomla will show such a message as:  AI Sentiment: positive

Or you can save the response in a custom field and present it on the front end.


Bonus Tips:

  • Store your API key securely in Joomla’s configuration or an environment variable (not hard-coded).
  • Add caching if you’re analyzing large volumes of content.
  • Trim long text before sending to OpenAI to save API tokens.
  • Handle failed API calls gracefully with proper fallbacks.

Real-World Use Cases:

  • Highlight positive user reviews automatically.
  • Flag negative feedback for moderation.
  • Generate sentiment dashboards for community comments.
In the next part of our AI + PHP CMS series, we’ll move to Drupal 11, where we’ll build an AI Text Summarization module using PHP and OpenAI API.

Comments · 0