Artificial intelligence is changing the way we deal with user generated content. Sentiment analysis, or the automatic recognition of whether a comment or review or article is positive, negative, or neutral can be considered one of the most powerful applications.
In this tutorial, we are going to develop a basic Joomla content plug-in that is linked to the Open AI API. Each time an article or comment is saved the text will be processed by our plugin and the sentiment will be shown in Joomla where it belongs in the admin.
This can be considered an excellent representation of a merge between AI and the classic PHP CMS systems, such as Joomla.
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.
 
 
0 comments:
Post a Comment