Schritt 1: Erstellen Sie den Plugin-Ordner
Der erste Schritt bei der Erstellung eines WordPress-Plugins ist das Einrichten des Plugin-Ordners.
Öffnen Sie Ihren Datei-Explorer und erstellen Sie einen neuen Ordner namens 'AI-Product-Description-Generator'. Hier werden alle Ihre Plugin-Dateien gespeichert.
Schritt 2: Erstellen Sie die Haupt-Plugin-Datei
Öffnen Sie VS Code. Erstellen Sie im Ordner 'AI-Product-Description-Generator' eine neue Datei namens 'product-description.php'. Diese Datei enthält den gesamten Code für Ihr Plugin.
Schritt 3: Plugin-Header einrichten
Der erste Schritt bei der Erstellung eines WordPress-Plugins ist das Einrichten des Plugin-Headers. Diese einfache Codezeile teilt WordPress den Namen Ihres Plugins, seine Version und wer es erstellt hat mit.
<?php
/*
Plugin Name: AI-Powered Product Description Generator
Description: Generate product descriptions for WooCommerce products using the Gemini API.
Version: 1.5
Author: Urooj Shafait
Company: LoomVision.org
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Security check to prevent direct file access
}
Fügen Sie diesen Code in Ihre Datei 'product-description.php' ein. Achten Sie darauf, den 'Plugin Name', die 'Description', den 'Author' und die 'Company' an Ihre Bedürfnisse anzupassen.
Schritt 4: JavaScript-Integration
Fügen Sie JavaScript zu Produktseiten hinzu, um die Generierung von Beschreibungen zu ermöglichen.
function pdg_enqueue_admin_scripts(
$hook) {
if ($hook != 'post.php' && $hook != 'post-new.php') {
return; // Load only on product pages
}
global $post;
if ($post->post_type === 'product') {
wp_enqueue_script( 'jquery' );
wp_add_inline_script('jquery', '
jQuery(document).ready(function($) {
function generateContent(type) {
var productName = $("#title").val();
var productSKU = $("#sku").val();
var productPrice = $("#_regular_price").val();
var productWeight = $("#_weight").val();
if (!productName) {
alert("Please ensure the product name is filled in.");
return;
}
$("#pdg-loading").show();
$.ajax({
type: "POST",
url: pdg_ajax_obj.ajax_url,
data: {
action: 'pdg_handle_description_generation',
pdg_nonce: pdg_ajax_obj.nonce, // Nonce for security
product_name: productName,
product_sku: productSKU,
product_price: productPrice,
product_weight: productWeight,
type: type
},
success: function(response) {
if (response.success) {
var content = response.data.content;
if (type == "short_description"){
if (typeof tinyMCE !== 'undefined' && tinyMCE.get("excerpt")) {
tinyMCE.get("excerpt").setContent(content);
}else{
$("#excerpt").val(content);
}
}else{
if (typeof tinyMCE !== 'undefined' && tinyMCE.get("content")) {
tinyMCE.get("content").setContent(content);
} else {
$("#content").val(content);
}
}
} else {
alert("Sorry, something went wrong: " + response.data.message);
}
},
complete: function() {
$("#pdg-loading").hide();
},
error: function(jqXHR, textStatus, errorThrown) {
console.error("AJAX error: " + textStatus + ' ' + errorThrown);
alert("AJAX error: " + textStatus + ' ' + errorThrown);
}
});
}
// Append Generate Product Description Button next to Add Media Button in Product Description
$("#wp-content-media-buttons").append('<button type="button" id="pdg-generate-description" class="button">Generate Product Description</button>');
// Append Generate Short Description Button next to Add Media Button in Short Product Description
$("#wp-excerpt-media-buttons").append('<button type="button" id="pdg-generate-short-description" class="button">Generate Short Description</button>');
//Add button click handlers
$("#pdg-generate-description").on("click", function() {
generateContent("description");
});
$("#pdg-generate-short-description").on("click", function() {
generateContent("short_description");
});
});
wp_localize_script( 'jquery', 'pdg_ajax_obj', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'pdg_nonce' ),
));
}
}
add_action('admin_enqueue_scripts', 'pdg_enqueue_admin_scripts');
Dieser Code fügt die Schaltflächen 'Generate Product Description' und 'Generate Short Description' neben den Schaltflächen 'Add Media' im Produkteditor hinzu. Er fügt auch Klick-Handler hinzu, um die Inhaltsgenerierungsfunktion zu starten.
Schritt 5: AJAX-Anforderungen verarbeiten
Das Ziel dieses Abschnitts ist es, eine serverseitige Logik zu implementieren, um mithilfe der Gemini-API Beschreibungen zu generieren.
function pdg_handle_description_generation() {
check_ajax_referer( 'pdg_nonce', 'security' );
$product_name = sanitize_text_field($_POST['product_name']);
$product_sku = sanitize_text_field($_POST['product_sku']);
$product_price = sanitize_text_field($_POST['product_price']);
$product_weight = sanitize_text_field($_POST['product_weight']);
$type = sanitize_text_field($_POST['type']);
// Your Api Key
$api_key = 'YOUR_API_KEY'; // Replace with your actual API key
$api_url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=' . $api_key;
$headers = [
'Content-Type' => 'application/json'
];
if($type == "short_description"){
$prompt = "Generate a concise and engaging product short description formatted in markdown. Avoid including the product name, SKU, or price in the description. Use clear and descriptive language to highlight the key features and benefits:
Product Name: {
$product_name}
SKU: {
$product_sku}
Price: {
$product_price}
Weight: {
$product_weight}
Focus on providing a short and appealing summary of the product's key attributes.";
}else{
$prompt = "Generate a detailed and engaging product description formatted in markdown. Use headings, bullet points, and formatting to showcase the product's features.
Make sure the description is rich in content and well-formatted without any unwanted characters.
Product Name: {
$product_name}
SKU: {
$product_sku}
Price: {
$product_price}
Weight: {
$product_weight}
";
}
$body = json_encode([
'contents' => [
['parts' => [['text' => $prompt]]],
],
]);
$args = [
'method' => 'POST',
'headers' => $headers,
'body' => $body,
'timeout' => 30,
];
$response = wp_remote_post( $api_url, $args );
if ( is_wp_error( $response ) ) {
wp_send_json_error( [ 'message' => 'Failed to get response from Gemini API: ' . $response->get_error_message() ] );
return;
}
$response_body = wp_remote_retrieve_body( $response );
$data = json_decode( $response_body, true );
if (json_last_error() !== JSON_ERROR_NONE) {
wp_send_json_error(['message' => 'Invalid JSON response from Gemini API:' . json_last_error_message()]);
return;
}
if (isset($data['candidates'][0]['content']['parts'][0]['text'])) {
$responseText = $data['candidates'][0]['content']['parts'][0]['text'];
$responseText = trim($responseText);
$responseText = convert_markdown_to_html($responseText);
wp_send_json_success(['content' => $responseText]);
} else {
wp_send_json_error(['message' => 'Unexpected response format from Gemini API']);
}
wp_die(); // Always include wp_die() at the end of AJAX functions
}
add_action('wp_ajax_pdg_handle_description_generation', 'pdg_handle_description_generation');
add_action('wp_ajax_nopriv_pdg_handle_description_generation', 'pdg_handle_description_generation');
Ersetzen Sie YOUR_API_KEY durch Ihren Gemini API-Schlüssel. Dieser Code ruft die AJAX-Anforderung ab, bereinigt die Eingabe, sendet Daten an die Gemini API und gibt die generierte Beschreibung zurück.
Schritt 6: Markdown in HTML konvertieren
Konvertieren Sie Markdown in HTML, um eine korrekte Anzeige sicherzustellen.
function convert_markdown_to_html($text) {
$text = preg_replace('/###\s+(.*)/m', '<h3>$1</h3>', $text);
$text = preg_replace('/##\s+(.*)/m', '<h2>$1</h2>', $text);
$text = preg_replace('/#\s+(.*)/m', '<h1>$1</h1>', $text);
$text = preg_replace('/\*\s+\[\s\*-+(.*)\]/s', '<ul><li>$1</li></ul>', $text);
$text = preg_replace('/<li>\s*<\/li>/s', '<ul></ul>', $text);
$text = preg_replace('/\*\s+(.*)\*\s*/', '<strong>$1</strong>', $text);
$text = preg_replace('/\*(.*)\*/', '<em>$1</em>', $text);
$text = preg_replace('/
{2,}/', '<p>', $text);
$text = preg_replace('/[\d]\. |[a-z]\. (.*)/', '<li>$1</li>', $text);
$text = trim($text);
if (!preg_match('/<p>.*<\/p>/s', $text)) {
$text = '<p>' . $text . '</p>';
}
return $text;
}
Dieser Code verwendet reguläre Ausdrücke, um Markdown-Inhalte in HTML zu konvertieren, wodurch eine ordnungsgemäße Formatierung im WordPress-Editor sichergestellt wird.