Writing product descriptions manually is slow, repetitive, and expensive — especially if you manage a large Magento store. But what if Magento could auto-generate SEO-friendly product descriptions using AI?
In this guide, you’ll learn how to integrate OpenAI’s API into Magento 2 to automatically generate product descriptions, short descriptions, and meta tags — directly from the Admin panel.
This is the next part of our AI + PHP CMS frameworks series.
What we are going to build
- A button in Magento 2 for the admin that says "Generate AI Description"
- An AJAX controller that sends product attributes to OpenAI
- A description, short description, and meta content made by AI
- Automatic insertion into Magento product fields
- Optional: button to regenerate to get better results
Requirements
- Magento 2.4+
- PHP 8.1+
- Composer
- An OpenAI API key
- Basic module development skills
Step 1: Create a Magento Module Skeleton
Create your module folders:
app/code/AlbertAI/ProductDescription/
Inside it, create registration.php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'AlbertAI_ProductDescription',
__DIR__
);
Then create etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="AlbertAI_ProductDescription" setup_version="1.0.0"/>
</config>
Enable the module:
php bin/magento setup:upgrade
Step 2: On the Product Edit Page, add a button that says "Generate Description."
Create a file: view/adminhtml/layout/catalog_product_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="product_form">
<block class="AlbertAI\ProductDescription\Block\Adminhtml\GenerateButton"
name="ai_description_button"/>
</referenceBlock>
</body>
</page>
Step 3: Create the Admin Button Block
File: Block/Adminhtml/GenerateButton.php
namespace AlbertAI\ProductDescription\Block\Adminhtml;
use Magento\Backend\Block\Template;
class GenerateButton extends Template
{
protected $_template = 'AlbertAI_ProductDescription::button.phtml';
}
Step 4: The Button Markup
File: view/adminhtml/templates/button.phtml
<button id="ai-generate-btn" class="action-default scalable primary">
Generate AI Description
</button>
<script>
require(['jquery'], function ($) {
$('#ai-generate-btn').click(function () {
const productId = $('#product_id').val();
$.ajax({
url: 'getUrl("ai/generator/description") ?>',
type: 'POST',
data: { product_id: productId },
success: function (res) {
if (res.success) {
$('#description').val(res.description);
$('#short_description').val(res.short_description);
$('#meta_description').val(res.meta_description);
alert("AI description ready!");
} else {
alert("Error: " + res.error);
}
}
});
});
});
</script>
Step 5: Create an Admin Route
File: etc/adminhtml/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="ai" frontName="ai">
<module name="AlbertAI_ProductDescription"/>
</route>
</router>
</config>
Step 6: Build the AI Controller That Calls OpenAI
File: Controller/Adminhtml/Generator/Description.php
namespace AlbertAI\ProductDescription\Controller\Adminhtml\Generator;
use Magento\Backend\App\Action;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Controller\Result\JsonFactory;
class Description extends Action
{
protected $jsonFactory;
protected $productRepo;
private $apiKey = "YOUR_OPENAI_API_KEY";
public function __construct(
Action\Context $context,
ProductRepositoryInterface $productRepo,
JsonFactory $jsonFactory
) {
parent::__construct($context);
$this->productRepo = $productRepo;
$this->jsonFactory = $jsonFactory;
}
public function execute()
{
$result = $this->jsonFactory->create();
$id = $this->getRequest()->getParam('product_id');
if (!$id) {
return $result->setData(['success' => false, 'error' => 'Product not found']);
}
$product = $this->productRepo->getById($id);
$prompt = sprintf(
"Write an SEO-friendly product description.\nProduct Name: %s\nBrand: %s\nFeatures: %s\nOutput: Long description, short description, and meta description.",
$product->getName(),
$product->getAttributeText('manufacturer'),
implode(', ', $product->getAttributes())
);
$generated = $this->generateText($prompt);
return $result->setData([
'success' => true,
'description' => $generated['long'],
'short_description' => $generated['short'],
'meta_description' => $generated['meta']
]);
}
private function generateText($prompt)
{
$body = [
"model" => "gpt-4.1-mini",
"messages" => [
["role" => "user", "content" => $prompt]
]
];
$ch = curl_init("https://api.openai.com/v1/chat/completions");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer " . $this->apiKey
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($body)
]);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
$text = $response['choices'][0]['message']['content'] ?? "No response";
// Split via sections
return [
'long' => $this->extract($text, 'Long'),
'short' => $this->extract($text, 'Short'),
'meta' => $this->extract($text, 'Meta')
];
}
private function extract($text, $type)
{
preg_match("/$type Description:\s*(.+)/i", $text, $m);
return $m[1] ?? $text;
}
}
Step 7: Test It
- Go to Magento Admin → Catalog → Products
- Edit any product
- Click “Generate AI Description”
- Descriptions fields will auto-fill in seconds
Bonus Tips
You can extend the module to generate:
- Product titles
- Bullet points
- FAQ sections
- Meta keywords
- Category descriptions
Next up, we’ll build a AI Auto-Tagging System for Laravel Blogs Using Embeddings + Cron Jobs.
0 comments:
Post a Comment