7 Commits

Author SHA1 Message Date
5ddd3f8104 feat: Update version to 1.7.0 and add term description length settings for AI-generated content 2026-01-30 11:57:21 +00:00
9df41ca85c chore: Bump version to 1.6.4 and update OAuth redirect URI descriptions 2026-01-26 19:50:38 +00:00
934cbf0f73 chore: Bump version to 1.6.3 2026-01-26 19:26:20 +00:00
5cc6e869bf Refactor code structure for improved readability and maintainability 2026-01-26 19:25:42 +00:00
79d411f35a feat: Register plugin settings with WordPress 2026-01-23 19:02:11 +00:00
58a9b37ccf Add bulk term generation functionality and enhance logging
- Introduced a new JavaScript file for handling bulk term generation in the admin interface.
- Implemented AJAX requests for generating terms and handling responses with appropriate logging.
- Enhanced the Groq_AI_Ajax_Controller to support new options for term generation, including origin and force parameters.
- Improved error handling and logging for term generation events.
- Updated the user interface to reflect the status of term generation and provide feedback to the user.
2026-01-23 18:55:52 +00:00
5b256f1374 feat: Implement bulk generation for category descriptions with AJAX handling 2026-01-23 18:25:15 +00:00
11 changed files with 2110 additions and 1330 deletions

53
AGENTS.md Normal file
View File

@@ -0,0 +1,53 @@
# AGENTS Repo handleiding
## Context & scope
- Deze repository bevat de volledige WordPress-plugin **SitiAI Product Teksten** inclusief assets, taalbestanden en Docker-configs. Alle pluginbestanden leven hier (geen submodules).
- Doel: AI-gestuurde content genereren voor WooCommerce-producten en -termen met ondersteuning voor Groq, OpenAI en Google Gemini plus Rank Math & Google integraties.
- Belangrijkste entrypoints: `groq-ai-product-text.php` (bootstrap), `includes/` (services, admin UI, providers) en `assets/` (admin CSS/JS).
## Lokale ontwikkelworkflow
1. Vereisten: Docker Desktop/Engine met Compose v2. Verdere tooling (npm, composer) is niet nodig; assets staan reeds gecompileerd.
2. Start omgeving:
```bash
docker compose up --build -d
```
- WordPress: http://localhost:8082
- phpMyAdmin: http://localhost:8085
- MariaDB poort 3307 (db/user/pass = `wordpress`)
3. WordPress installatie afronden via de browser, WooCommerce + deze plugin activeren.
4. Handige commandos:
- `docker compose exec wordpress bash`
- `docker compose exec wordpress wp plugin list`
- `docker compose logs -f wordpress`
- Stoppen/herinitialiseren: `docker compose down` / `docker compose down -v`
5. Code staat buiten containers (bind mount). Gebruik git op de host (`git status`, `git commit`, …).
## Code style & patronen
- Hanteer WordPress/PHP Coding Standards: tabs voor indent, `esc_html__`, `esc_attr__`, `wp_nonce_field`, etc. Tekstdomein = `siti-ai-product-content-generator`.
- Alle adminstrings moeten vertaalbaar zijn via `__()`/`_e()`.
- Integreer met bestaande services via `Groq_AI_Service_Container`; voeg nieuwe services via `$container->set()` in `groq-ai-product-text.php`.
- Houd prompts/JSON-structuren consistent met `Groq_AI_Prompt_Builder`. Als je outputfields toevoegt, zorg ook voor updates in `get_structured_response_instructions()` en de UI (`assets/js/admin.js`).
- AJAX-acties zitten in `Groq_AI_Ajax_Controller`; vervolgacties moeten capability checks, nonce-validatie en wp_send_json_* gebruiken.
- Voor settings gebruik je altijd `Groq_AI_Settings_Manager` zodat defaults, sanitization en modules consistent blijven.
- Houd rekening met de Rank Math module (optioneel) en Google OAuth flows (Search Console / GA clients). Voeg configuratie-opties toe via de bestaande adminpaginas en filters.
## Testen & QA
- Geen geautomatiseerde test-suite beschikbaar. Valideer wijzigingen door de Docker-WordPress te gebruiken.
- PHP-lint: `docker compose exec wordpress php -l /var/www/html/wp-content/plugins/siti-ai-product-content-generator/<bestand>`.
- Controleer AI-flows handmatig: productmodal, categorie/merk generator, bulk acties en AI-logboek.
- Controleer database-migraties: logtabel `wp_groq_ai_generation_logs` wordt bij init aangemaakt. Gebruik WP-CLI of phpMyAdmin om schemawijzigingen te verifiëren.
- Houd WooCommerce actief; de plugin deactiveert zichzelf als WooCommerce ontbreekt.
## Release & versiebeheer
1. Pas `Version` (en eventueel `Stable tag`) aan in `groq-ai-product-text.php`.
2. Commit veranderingen en push naar `main` of start handmatig de workflow **Build & Release Plugin** (GitHub Actions).
3. Workflow bouwt zip, maakt tag `vX.Y.Z` en publiceert een release. Live sites krijgen updates via `SitiWebUpdater`.
4. Bewaak backwards compatibility; logs en prompts worden opgeslagen in WordPress options/meta.
## Overige tips & valkuilen
- `rg` is momenteel niet geïnstalleerd in deze omgeving; gebruik `grep`/`fd` voor zoekopdrachten.
- Geef altijd capability-checks en nonce-validatie wanneer je nieuwe admin-acties toevoegt.
- Filters ter beschikking: `groq_ai_brand_taxonomy`, `groq_ai_model_exclusions`, `groq_ai_term_google_context`, enz. Gebruik die in plaats van hardcodings.
- Afbeeldingscontext kan `url`, `base64` of `none` zijn. Nieuwe providers moeten dit ondersteunen of duidelijk aangeven dat het unsupported is.
- Denk aan caching (transients) zoals `Groq_AI_Google_Context_Builder` doet; intensieve API-calls moeten nooit in loops zonder caching draaien.
- Logging (`Groq_AI_Generation_Logger`) is essentieel voor support. Als je nieuwe AI-calls toevoegt, log status, tokens en fouten daar.

157
README.md
View File

@@ -1,93 +1,110 @@
# SitiAI Product Teksten (WordPress plugin)
Deze repository bevat de WordPress plugin waarmee productteksten via SitiAI kunnen worden gegenereerd. De plugincode leeft volledig in deze map en kan daarom veilig via git beheerd worden.
SitiAI Product Teksten voegt een AI-gestuurde workflow toe aan WooCommerce zodat redacties product-, categorie- en merkteksten rechtstreeks binnen WordPress kunnen genereren. De plugin bundelt alle logica in deze repository (inclusief assets, taalbestanden en Docker-omgeving) en kan daardoor geheel via git beheerd en gedeployed worden.
## Plugin installeren en gebruiken
## Functionaliteiten in vogelvlucht
- **Multi-provider AI**: selecteer Groq, OpenAI of Google Gemini en laad live model-lijsten. `Groq_AI_Model_Exclusions` filtert ongeschikte modellen en elke provider declareert eigen endpoint, API-sleutel en resp. JSON capabilities.
- **WooCommerce productmodal**: op de productbewerkscherm verschijnt de meta-box “Gebruik AI” met een modal waarin gebruikers prompts kunnen sturen, contextvelden (titel, beschrijvingen, attributen, merken, afbeeldingen) kunnen toggelen en resultaten per veld kunnen kopiëren of direct invullen.
- **Categorie- en merkteksten**: uitgebreide beheerschermen voor `product_cat` en gedetecteerde merk-taxonomieën bevatten overzichten met woordtellingen, bulk-acties en een termgenerator die topverkopers, interne links en (optioneel) Google-data toevoegt. Output splitst in bovenste beschrijving, onderste beschrijving en indien Rank Math actief SEO-velden.
- **Prompt builder & contextbeheer**: `Groq_AI_Prompt_Builder` bouwt system prompts op basis van winkelcontext, gefixeerde conversation IDs en geselecteerde contextvelden. Productprompts eisen strikt JSON volgens `get_structured_response_instructions`; termprompts gebruiken desgewenst OpenAI/Groq response_format.
- **Modules**: de Rank Math-module is standaard beschikbaar en bepaalt focuskeywordlimieten plus pixel-limieten voor meta title/description. Modules zijn uitbreidbaar via filters en krijgen een eigen instellingenpagina.
- **Google-integratie**: OAuth 2.0 koppeling met Search Console en GA4 voegt queries, sessies en engaged sessions toe aan termcontext. Tokens worden ververst via `Groq_AI_Google_OAuth_Client` en resultaten gecachet (15 min).
- **Logging & audits**: alle generaties worden opgeslagen in `wp_groq_ai_generation_logs` met prompt, response, status en token usage. Er zijn admin-schermen voor log-overzichten en detailpaginas.
- **Live updates**: `SitiWebUpdater` controleert GitHub releases (`SitiWeb/siti-ai-product-content-generator`) en verzorgt binnen WordPress één-klik updates inclusief re-activatie.
### Systeemeisen
## Vereisten
- WordPress 6.4+ en WooCommerce (de plugin deactiveert zichzelf zonder WooCommerce).
- PHP 8.0+ (de Dockerfile gebruikt WordPress 6.9 op PHP 8.2).
- Minstens één AI API-sleutel (Groq, OpenAI of Google Gemini). Je kunt sleutels voor meerdere providers opslaan en later wisselen.
- Optioneel: Rank Math SEO (voor extra velden) en Google Cloud-project met Search Console & GA4 toegang voor OAuth.
- WordPress 6.4 of hoger.
- WooCommerce (de plugin controleert dit en deactiveert zichzelf als WooCommerce ontbreekt).
- Minimaal één API-sleutel voor Groq, OpenAI of Google Gemini.
- (Optioneel) Rank Math SEO wanneer je de extra SEO-velden wilt gebruiken.
### Installatie
1. Download de nieuwste release (`siti-ai-product-content-generator-x.y.z.zip`) vanaf de [GitHub Releases](https://github.com/SitiWeb/siti-ai-product-content-generator/releases) of gebruik het zip-bestand dat door de workflow in `dist/` wordt geplaatst.
2. Ga in WordPress naar **Plugins → Nieuwe plugin → Plugin uploaden** en upload het zipbestand. Je kunt de map ook handmatig naar `wp-content/plugins/` uploaden.
## Installatie & activatie
### Plugin installeren
1. Download de laatste release (`siti-ai-product-content-generator-x.y.z.zip`) vanuit GitHub Releases of gebruik het zip-bestand dat door de workflow in `dist/` verschijnt.
2. Upload via **Plugins → Nieuwe plugin → Plugin uploaden** of plaats de map onder `wp-content/plugins/`.
3. Activeer **SitiAI Product Teksten** en controleer dat WooCommerce actief is.
### Configuratie
1. Navigeer naar **Instellingen → Siti AI**.
2. Kies een AI-aanbieder, vul de bijbehorende API-sleutel in en (optioneel) klik op **Live modellen ophalen** om beschikbare modellen te laden.
3. Stel een standaard prompt en winkelcontext in zodat het AI-venster vooraf gevuld is.
4. Selecteer welke productvelden standaard als context dienen (titel, beschrijvingen, attributen, …).
5. Gebruik de knop **Ga naar modules** om bijvoorbeeld de Rank Math integratie aan of uit te zetten en de limieten aan te passen.
6. Via **Bekijk AI-logboek** zie je alle eerdere generaties inclusief foutmeldingen of token usage.
### Basisconfiguratie
1. Ga naar **Instellingen → Siti AI**.
2. Kies een provider, stel het standaardmodel in (of laad live modellen via de knop), vul de bijbehorende API-sleutel in en kies optioneel andere aanbieders.
3. Vul winkelcontext, standaardprompt, maximale outputtokens en gewenste contextvelden. Via **Prompt & context** beheer je defaults voor attributen, merkdetectie, beeldcontext (`none`, `url`, `base64`) en het maximale aantal afbeeldingen.
4. Stel modules (Rank Math) in via **Instellingen → Siti AI → Modules** om keywordlimieten/pixellimieten te wijzigen en de module te activeren/deactiveren.
5. (Optioneel) Koppel Google OAuth (client ID/secret + refresh token) en configureer Search Console site + GA4 property. Gebruik de ingebouwde verbindingstest om scopes te bevestigen.
6. Gebruik op het tabblad **Prompt & context** de velden *Term omschrijving lengte* om de gewenste tekentaantallen voor de korte (top) en lange (bottom) categorie-/merktekst vast te leggen. De AI krijgt deze waardes met een marge van ±10%.
### Productteksten genereren
1. Open een WooCommerce-product en klik in de meta-box op **Gebruik AI**.
2. De modal toont de standaardprompt, contextselecties en (indien ingesteld) standaard attributen. Je kunt contextvelden tijdelijk toggelen zonder globale instellingen te wijzigen.
3. Na **Genereer tekst** verschijnt output per veld: titel (inclusief drie suggesties), slug, korte beschrijving, beschrijving en indien Rank Math module meta title, meta description en focus keywords. Met de knoppen kun je de inhoud kopiëren of rechtstreeks invoegen in de corresponderende WordPress velden.
4. Iedere call wordt gelogd (status, tokens, provider) en kan via het AI-logboek worden ingezien.
5. Ajax-acties: `groq_ai_generate_text` verwerkt productprompts, `groq_ai_refresh_models` haalt provider-specifieke modellen op.
1. Open een product in WooCommerce en gebruik de meta-box **Gebruik AI** om de modal te openen.
2. Vul (of hergebruik) een prompt, kies welke contextvelden meegestuurd worden en klik op **Genereer tekst**.
3. De resultaten verschijnen per veld (titel, korte beschrijving, beschrijving en indien geactiveerd Rank Math velden). Gebruik **Kopieer** of **Vul … in** om velden direct over te nemen.
4. Via de geavanceerde sectie kun je contextvelden tijdelijk uitschakelen; dit heeft alleen effect voor de huidige generatie.
5. Iedere generatie wordt opgeslagen in het AI-logboek zodat je binnen WordPress kunt terugzoeken wat er is gebeurd.
### Categorie- en merkteksten
- Ga naar **Instellingen → Siti AI → Categorieën** of **Merken** om een overzicht te zien met productcounts en woordtellingen. Lege termen worden gemarkeerd.
- Bovenaan staat een bulk-paneel dat een achtergrondproces start (`groq_ai_bulk_generate_terms`) voor lege termen; optioneel kun je bestaande teksten forceren.
- Klik op een term om naar de generator te gaan. Daar kun je bovenste en onderste beschrijvingen, Rank Math velden en een term-specifieke prompt beheren. De knop **Genereer** roept `groq_ai_generate_term_text` aan, toont ruwe JSON-output en stelt je in staat de velden met één klik te vullen.
- Context bevat: termnaam/slug/productcount, bestaande beschrijvingen (ook custom meta), topverkopende producten (max 25), automatische interne link-suggesties, merkcontext en indien geactiveerd Search Console queries en GA4 sessies.
- Via de ingestelde tekentaantallen weet de AI hoeveel inhoud de korte en lange omschrijving ongeveer moeten bevatten; hij stuurt automatisch bij binnen ±10%.
## Ontwikkelvereisten
### Modules & integraties
- **Rank Math**: bepaalt of focuskeywords + meta velden worden getoond/bewaard bij zowel producten als termen. Limieten (keywords, pixelbreedtess) worden afgedwongen in de promptinstructies en validatie.
- **Google-data**: caching en foutafhandeling gebeurt binnen de serviceclient. Errors verschijnen als WP notices en in het log. Zorg dat de redirect-URL (`/wp-admin/admin-post.php?action=groq_ai_google_oauth_callback`) in Google Cloud staat.
- **Response-format compatibiliteit**: toggle onder Algemene instellingen om JSON Schema mode te forceren wanneer een provider geen native `response_format` ondersteunt.
- Docker Desktop of Docker Engine + Docker Compose v2
### AI-logboek & troubleshooting
- Via **Instellingen → Siti AI → AI-logboek** heb je een WP_List_Table met filters, zoekveld en pagination. Klik op een regel om de detailpagina te zien (prompt, response, tokens, foutmelding, gekoppeld product en gebruiker).
- De `Groq_AI_Generation_Logger` creëert automatisch de DB-tabel bij `plugins_loaded`; bij ontbrekende tabellen kun je `WP_DEBUG` gebruiken om fouten te lezen.
- Alle fouten worden ook verstuurd naar `WC_Logger` (indien aanwezig) met bron `groq-ai-product-text`.
## Ontwikkelen in de Docker omgeving
## Hooks & extensies
- `groq_ai_brand_taxonomy` / `groq_ai_brand_taxonomy_candidates`: overschrijf detectie van merk-taxonomie.
- `groq_ai_product_brand_context`: wijzig de tekst die voor merkcontext wordt meegestuurd.
- `groq_ai_term_google_context`: voeg extra analytics of SEO-data toe aan termcontext.
- `groq_ai_model_exclusions`: pas geblokkeerde modellen per provider aan.
- `groq_ai_prompt_default_context_fields`: stel andere standaardcontextvelden in.
- `groq_ai_bulk_term_generation_options`: beïnvloed bulk-run opties (bijv. aantal top-producten).
- Algemene WordPress filters zoals `plugin_action_links` of `admin_menu` kunnen gebruikt worden voor extra UI-knoppen; `Groq_AI_Service_Container` maakt het eenvoudig om services te vervangen of uit te breiden.
1. Start de containers (WordPress + MariaDB + phpMyAdmin):
```bash
docker compose up --build -d
```
2. Open http://localhost:8080 om de WordPress installatie te doorlopen. Gebruik `db` als host en de volgende databasegegevens:
- database: `wordpress`
- gebruiker: `wordpress`
- wachtwoord: `wordpress`
3. Activeer in het WordPress dashboard de plugin **SitiAI Product Teksten** (deze repository wordt in de container gemount naar `wp-content/plugins/siti-ai-product-content-generator`).
### Handige commando's
- Shell in de WordPress container om bijvoorbeeld `wp` CLI of git te draaien binnen de container:
```bash
docker compose exec wordpress bash
```
- WP-CLI is al aanwezig:
```bash
docker compose exec wordpress wp plugin list
```
- Bekijk de database via phpMyAdmin op http://localhost:8081 (gebruik dezelfde DB-gebruiker/WW als hierboven).
- Containers stoppen:
```bash
docker compose down
```
## Werken met git
De pluginbestanden blijven op de host staan en worden alleen als bind-mount in de container gebruikt. Daardoor kun je git gewoon op je machine gebruiken:
## Lokale ontwikkeling
### Voorwaarden
- Docker Desktop of Docker Engine + Docker Compose v2.
- Node of build tooling is niet vereist; alle assets staan reeds gecompileerd in `assets/`.
### Containers starten
```bash
git status
git add .
git commit -m "Beschrijf je wijziging"
git push origin <branch>
docker compose up --build -d
```
- WordPress: http://localhost:8082
- phpMyAdmin: http://localhost:8085
- MariaDB: poort 3307 (database, user, wachtwoord = `wordpress`)
Je kunt optioneel vanuit de container git gebruiken (zelfde codepad) wanneer je liever binnen Docker werkt.
### WordPress initialiseren
1. Bezoek http://localhost:8082 en volg de standaard WordPress-installatie (gebruik de `db` host en bovengenoemde databasegegevens).
2. Log in, activeer WooCommerce (indien niet automatisch) en activeer daarna **SitiAI Product Teksten**. De plugin is als bind-mount aanwezig onder `wp-content/plugins/siti-ai-product-content-generator`.
## Tips
### Handige commandos
- Shell binnen de WordPress-container: `docker compose exec wordpress bash`
- WP-CLI gebruiken: `docker compose exec wordpress wp plugin list`
- Logs volgen: `docker compose logs -f wordpress`
- Containers stoppen: `docker compose down`
- Helemaal opnieuw beginnen (verwijdert volumes): `docker compose down -v`
- De databank (`db_data`) en WordPress bestanden (`wordpress_data`) worden in Docker volumes opgeslagen zodat je data behouden blijft tussen sessies.
- Wil je helemaal opnieuw beginnen? Voer `docker compose down -v` uit om de volumes te verwijderen.
Alle code staat buiten de container, dus je kunt op de host `git status`, `git commit` etc. draaien. De Dockerfile (WordPress 6.9 / PHP 8.2) installeert hulpmiddelen zoals git, wp-cli en mariadb-client.
## Releasen via GitHub Actions
## Release & updates
1. Verhoog de `Version` header in `groq-ai-product-text.php` en commit de wijzigingen.
2. Push naar `main` of start handmatig de GitHub Action **Build & Release Plugin**. De workflow creëert een distributie-zip, maakt tag `vX.Y.Z` en publiceert een GitHub Release met asset.
3. Productiesites met de plugin krijgen een update-notificatie via `SitiWebUpdater` en kunnen vanuit het WordPress dashboard upgraden.
De workflow `.github/workflows/release.yml` bouwt automatisch een distributie-zip van de plugin, maakt een git-tag (`vX.Y.Z`) op basis van de versie in `groq-ai-product-text.php` en publiceert een GitHub Release met het zipbestand als asset.
## Mappenstructuur
- `groq-ai-product-text.php`: hoofdbestand dat services, providers, admin-schermen en hooks initialiseert.
- `includes/Core`: service container, AJAX-controller en model-exclusiehulpen.
- `includes/Admin`: instellingenpaginas, meta-box UI, logboek en termoverzichten.
- `includes/Providers`: implementaties voor Groq, OpenAI en Google (Gemini), inclusief live model listing en requestafhandeling.
- `includes/Services`: gedeelde services zoals prompt builder, settings manager, conversatiebeheer, logging en Google-clients.
- `assets/css` & `assets/js`: statische bestanden voor de WordPress admin experience.
- `languages`: `.po/.mo` bestanden voor vertalingen.
- `docker` + `docker-compose.yml`: lokale ontwikkelomgeving.
- `snippets` & `assets/img`: aanvullende hulpmiddelen en marketingmateriaal.
1. Werk de `Version`-header in `groq-ai-product-text.php` bij en commit de wijzigingen.
2. Push naar `main` of start handmatig de workflow **Build & Release Plugin** via **Actions → Run workflow** (optioneel met extra release notes).
3. De workflow slaat releases over wanneer een tag met dezelfde versie al bestaat.
Met deze README heb je een startpunt voor zowel functionele gebruikers (hoe gebruik ik de plugin) als ontwikkelaars (hoe werkt de codebase, hoe ontwikkel ik lokaal, hoe release ik). Vragen of verbeteringen? Open een issue of start een PR.

View File

@@ -33,7 +33,7 @@ class SitiWebUpdater {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$this->plugin = get_plugin_data( $this->file );
$this->plugin = get_plugin_data( $this->file, false, false );
$this->basename = plugin_basename( $this->file );
$this->active = is_plugin_active( $this->basename );
}

View File

@@ -29,3 +29,80 @@
align-items: center;
margin-top: 8px;
}
.groq-ai-bulk-panel {
margin: 16px 0;
padding: 16px;
background: #fff;
border: 1px solid #dcdcde;
}
.groq-ai-bulk-panel .description {
margin-top: 8px;
}
.groq-ai-bulk-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
margin-top: 8px;
}
#groq-ai-bulk-status {
margin-top: 8px;
}
#groq-ai-bulk-status[data-status='error'] {
color: #b32d2e;
}
#groq-ai-bulk-status[data-status='success'] {
color: #008a20;
}
.groq-ai-bulk-log {
margin: 12px 0 0;
padding-left: 18px;
max-height: 220px;
overflow-y: auto;
font-size: 13px;
}
.groq-ai-bulk-log li {
margin-bottom: 4px;
}
.groq-ai-bulk-log li[data-status='error'] {
color: #b32d2e;
}
.groq-ai-bulk-log li[data-status='success'] {
color: #008a20;
}
.groq-ai-term-row.groq-ai-term-missing td {
background: #fff8e5;
}
.groq-ai-term-row.groq-ai-term-updated td {
animation: groqAiTermPulse 1.8s ease-out 1;
}
@keyframes groqAiTermPulse {
from {
background-color: #e3f8eb;
}
to {
background-color: transparent;
}
}
.groq-ai-term-actions {
width: 180px;
}
.groq-ai-regenerate-term.is-busy {
opacity: 0.6;
pointer-events: none;
}

288
assets/js/term-bulk.js Normal file
View File

@@ -0,0 +1,288 @@
(function () {
const data = window.GroqAITermBulk || {};
const startButton = document.getElementById('groq-ai-bulk-generate');
const stopButton = document.getElementById('groq-ai-bulk-cancel');
const statusField = document.getElementById('groq-ai-bulk-status');
const logList = document.getElementById('groq-ai-bulk-log');
if (!data.ajaxUrl || !startButton || !statusField || !logList) {
return;
}
const strings = data.strings || {};
const allowRegenerate = !!data.allowRegenerate;
const terms = (Array.isArray(data.terms) ? data.terms : [])
.map((term) => {
const id = parseInt(term.id, 10);
if (!Number.isFinite(id)) {
return null;
}
const words = typeof term.words === 'number' ? term.words : parseInt(term.words, 10) || 0;
const hasDescription = !!term.hasDescription;
return {
id,
name: term.name || '',
slug: term.slug || '',
count: typeof term.count === 'number' ? term.count : parseInt(term.count, 10) || 0,
words,
hasDescription,
needsGeneration: !hasDescription,
};
})
.filter(Boolean);
const termMap = new Map();
terms.forEach((term) => termMap.set(term.id, term));
let queue = [];
let totalCount = 0;
let processed = 0;
let successes = 0;
let isRunning = false;
let abortRequested = false;
function formatString(template, values) {
if (!template) {
return '';
}
let autoIndex = 0;
return template.replace(/%(\d+\$)?[sd]/g, (match, position) => {
let valueIndex;
if (position) {
valueIndex = parseInt(position, 10) - 1;
} else {
valueIndex = autoIndex;
autoIndex += 1;
}
const replacement = values[valueIndex];
return typeof replacement === 'undefined' ? '' : String(replacement);
});
}
function setStatus(message, type) {
statusField.textContent = message || '';
statusField.dataset.status = type || '';
}
function appendLog(message, type) {
if (!message) {
return;
}
const item = document.createElement('li');
item.textContent = message;
item.dataset.status = type || '';
logList.appendChild(item);
}
function resetLog() {
logList.innerHTML = '';
}
function toggleButtons(running) {
isRunning = running;
startButton.disabled = running;
if (stopButton) {
stopButton.hidden = !running;
}
}
function getPendingTerms() {
return terms.filter((term) => term.needsGeneration);
}
function updateRow(term) {
const row = document.querySelector('[data-groq-ai-term-id="' + term.id + '"]');
if (!row) {
return;
}
row.classList.remove('groq-ai-term-missing');
row.classList.add('groq-ai-term-updated');
const wordCell = row.querySelector('.groq-ai-word-count');
if (wordCell) {
wordCell.textContent = String(term.words);
}
}
function markTermCompleted(term, words) {
term.hasDescription = true;
term.needsGeneration = false;
if (Number.isFinite(words)) {
term.words = words;
}
updateRow(term);
}
function finish(state) {
const summaryTemplate = state === 'done' ? strings.statusDone : state === 'stopped' ? strings.statusStopped : '';
const summary = summaryTemplate ? formatString(summaryTemplate, [successes]) : '';
const statusType = state === 'done' ? 'success' : state === 'stopped' ? 'info' : '';
setStatus(summary, statusType);
toggleButtons(false);
queue = [];
totalCount = 0;
processed = 0;
successes = 0;
abortRequested = false;
}
function sendRequest(term, options = {}) {
const payload = new URLSearchParams();
payload.append('action', 'groq_ai_bulk_generate_terms');
payload.append('nonce', data.nonce || '');
payload.append('taxonomy', data.taxonomy || '');
payload.append('term_id', term.id);
if (options.force) {
payload.append('force', '1');
}
return fetch(data.ajaxUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: payload.toString(),
}).then((response) => response.json());
}
function handleResponse(term, json, context) {
if (!json || !json.success) {
const errorMessage = (json && json.data && json.data.message) || 'Onbekende fout';
appendLog(formatString(strings.logError || '%1$s: %2$s', [term.name || term.id, errorMessage]), 'error');
if (context === 'single') {
setStatus(formatString(strings.regenerateError || '%1$s mislukt: %2$s', [term.name || term.id, errorMessage]), 'error');
}
return false;
}
const words = json.data && typeof json.data.words !== 'undefined' ? parseInt(json.data.words, 10) : term.words;
markTermCompleted(term, Number.isFinite(words) ? words : term.words);
appendLog(formatString(strings.logSuccess || '%1$s gevuld.', [term.name || term.id, term.words]), 'success');
if (context === 'single') {
setStatus(formatString(strings.regenerateDone || '%s is bijgewerkt.', [term.name || term.id]), 'success');
}
return true;
}
function processNext() {
if (abortRequested) {
finish('stopped');
return;
}
if (!queue.length) {
finish('done');
return;
}
const term = queue.shift();
const progressTemplate = strings.statusProgress;
if (progressTemplate) {
setStatus(formatString(progressTemplate, [processed + 1, totalCount, term.name || '']), 'loading');
}
sendRequest(term)
.then((json) => {
if (handleResponse(term, json, 'bulk')) {
successes += 1;
}
})
.catch((error) => {
appendLog(
formatString(strings.logError || '%1$s: %2$s', [term.name || term.id, error && error.message ? error.message : 'Onbekende fout']),
'error'
);
})
.finally(() => {
processed += 1;
if (abortRequested) {
finish('stopped');
} else {
processNext();
}
});
}
function startBulk() {
if (isRunning) {
return;
}
const pending = getPendingTerms();
if (!pending.length) {
setStatus(strings.statusEmpty || '', 'info');
return;
}
queue = pending.slice();
totalCount = queue.length;
processed = 0;
successes = 0;
abortRequested = false;
resetLog();
toggleButtons(true);
if (strings.statusIdle) {
setStatus(strings.statusIdle, 'info');
}
processNext();
}
startButton.addEventListener('click', startBulk);
if (stopButton) {
stopButton.addEventListener('click', () => {
if (!isRunning) {
return;
}
const confirmation = strings.confirmStop ? window.confirm(strings.confirmStop) : window.confirm('Stoppen?');
if (confirmation) {
abortRequested = true;
}
});
}
if (allowRegenerate) {
const buttons = document.querySelectorAll('.groq-ai-regenerate-term');
buttons.forEach((button) => {
button.addEventListener('click', () => {
if (isRunning) {
setStatus(strings.regenerateBlocked || '', 'error');
return;
}
const termId = parseInt(button.getAttribute('data-term-id'), 10);
const term = termMap.get(termId);
if (!term) {
setStatus('Onbekende term.', 'error');
return;
}
if (strings.confirmRegenerate) {
const confirmed = window.confirm(formatString(strings.confirmRegenerate, [term.name || term.id]));
if (!confirmed) {
return;
}
}
button.classList.add('is-busy');
button.disabled = true;
if (strings.regenerateProgress) {
setStatus(formatString(strings.regenerateProgress, [term.name || term.id]), 'loading');
}
sendRequest(term, { force: true })
.then((json) => {
handleResponse(term, json, 'single');
})
.catch((error) => {
const message = error && error.message ? error.message : 'Onbekende fout';
appendLog(formatString(strings.logError || '%1$s: %2$s', [term.name || term.id, message]), 'error');
setStatus(formatString(strings.regenerateError || '%1$s mislukt: %2$s', [term.name || term.id, message]), 'error');
})
.finally(() => {
button.disabled = false;
button.classList.remove('is-busy');
});
});
});
}
if (getPendingTerms().length === 0) {
setStatus(strings.statusEmpty || '', 'info');
}
})();

View File

@@ -2,7 +2,7 @@
/**
* Plugin Name: SitiAI Product Teksten
* Description: Genereer productteksten met diverse AI-aanbieders rechtstreeks vanuit WooCommerce.
* Version: 1.5.0
* Version: 1.7.0
* Author: SitiAI
* Text Domain: siti-ai-product-content-generator
* Domain Path: /languages
@@ -108,7 +108,6 @@ final class Groq_AI_Product_Text_Plugin {
$this->settings_page = new Groq_AI_Product_Text_Settings_Page( $this, $this->get_provider_manager() );
$this->product_ui = new Groq_AI_Product_Text_Product_UI( $this );
add_action( 'plugins_loaded', [ $this, 'maybe_load_textdomain_early' ], 0 );
add_action( 'init', [ $this, 'load_textdomain' ] );
add_action( 'plugins_loaded', [ $this, 'maybe_create_logs_table' ] );
add_action( 'load-plugins.php', [ $this, 'maybe_deactivate_if_woocommerce_missing' ] );
@@ -131,14 +130,6 @@ final class Groq_AI_Product_Text_Plugin {
$this->textdomain_loaded = true;
}
public function maybe_load_textdomain_early() {
if ( did_action( 'init' ) ) {
return;
}
$this->load_textdomain();
}
private function register_services() {
$this->container = new Groq_AI_Service_Container();
@@ -351,6 +342,14 @@ final class Groq_AI_Product_Text_Plugin {
return $this->get_settings_manager()->get_image_context_limit( $settings );
}
public function get_term_top_description_char_limit( $settings = null ) {
return $this->get_settings_manager()->get_term_top_description_char_limit( $settings );
}
public function get_term_bottom_description_char_limit( $settings = null ) {
return $this->get_settings_manager()->get_term_bottom_description_char_limit( $settings );
}
public function should_use_response_format( Groq_AI_Provider_Interface $provider, $settings ) {
return ! $this->is_response_format_compat_enabled( $settings ) && $provider->supports_response_format();
}

View File

@@ -136,28 +136,15 @@ class Groq_AI_Logs_Table extends WP_List_Table {
protected function column_created_at( $item ) {
$date = esc_html( mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $item['created_at'] ) );
$usage = $this->get_usage_meta( $item );
$payload = [
'created_at' => $item['created_at'],
'user' => $this->column_default( $item, 'user_id' ),
'post_title' => $item['post_title'],
'provider' => $item['provider'],
'model' => $item['model'],
'status' => $item['status'],
'tokens_prompt' => isset( $item['tokens_prompt'] ) ? (int) $item['tokens_prompt'] : null,
'tokens_completion' => isset( $item['tokens_completion'] ) ? (int) $item['tokens_completion'] : null,
'tokens_total' => isset( $item['tokens_total'] ) ? (int) $item['tokens_total'] : null,
'prompt' => $item['prompt'],
'response' => $item['response'],
'error_message' => $item['error_message'],
'image_context' => isset( $usage['image_context'] ) ? $usage['image_context'] : null,
];
$encoded = esc_attr( wp_json_encode( $payload ) );
return sprintf(
'<a href="#" class="groq-ai-log-row" data-groq-log="%s">%s</a>',
$encoded,
$date
$url = add_query_arg(
[
'page' => 'groq-ai-product-text-log',
'log_id' => isset( $item['id'] ) ? (int) $item['id'] : 0,
],
admin_url( 'options-general.php' )
);
return sprintf( '<a href="%s">%s</a>', esc_url( $url ), $date );
}
private function get_usage_meta( $item ) {

File diff suppressed because it is too large Load Diff

View File

@@ -10,6 +10,7 @@ class Groq_AI_Ajax_Controller {
add_action( 'wp_ajax_groq_ai_generate_text', [ $this, 'handle_generate_text' ] );
add_action( 'wp_ajax_groq_ai_refresh_models', [ $this, 'handle_refresh_models' ] );
add_action( 'wp_ajax_groq_ai_generate_term_text', [ $this, 'handle_generate_term_text' ] );
add_action( 'wp_ajax_groq_ai_bulk_generate_terms', [ $this, 'handle_bulk_generate_terms_request' ] );
}
public function handle_generate_term_text() {
@@ -35,6 +36,113 @@ class Groq_AI_Ajax_Controller {
wp_send_json_error( [ 'message' => __( 'Term niet gevonden.', GROQ_AI_PRODUCT_TEXT_DOMAIN ) ], 404 );
}
$result = $this->run_term_generation(
$term,
$prompt,
[
'include_top_products' => $include_top_products,
'top_products_limit' => $top_products_limit,
'origin' => 'term_manual',
]
);
if ( is_wp_error( $result ) ) {
wp_send_json_error( [ 'message' => $result->get_error_message() ], 500 );
}
wp_send_json_success( $result );
}
public function handle_bulk_generate_terms_request() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( [ 'message' => __( 'Je hebt geen toestemming voor deze actie.', GROQ_AI_PRODUCT_TEXT_DOMAIN ) ], 403 );
}
check_ajax_referer( 'groq_ai_bulk_generate_terms', 'nonce' );
$taxonomy = isset( $_POST['taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['taxonomy'] ) ) : '';
$term_id = isset( $_POST['term_id'] ) ? absint( $_POST['term_id'] ) : 0;
$force = ! empty( $_POST['force'] );
if ( '' === $taxonomy || ! taxonomy_exists( $taxonomy ) || ! $term_id ) {
wp_send_json_error( [ 'message' => __( 'Taxonomie en term_id zijn verplicht.', GROQ_AI_PRODUCT_TEXT_DOMAIN ) ], 400 );
}
$term = get_term( $term_id, $taxonomy );
if ( ! $term || is_wp_error( $term ) ) {
wp_send_json_error( [ 'message' => __( 'Term niet gevonden.', GROQ_AI_PRODUCT_TEXT_DOMAIN ) ], 404 );
}
$current_description = isset( $term->description ) ? trim( wp_strip_all_tags( (string) $term->description ) ) : '';
if ( '' !== $current_description && ! $force ) {
wp_send_json_error(
[
'message' => __( 'Categorie heeft al een omschrijving.', GROQ_AI_PRODUCT_TEXT_DOMAIN ),
'code' => 'groq_ai_term_has_description',
],
400
);
}
$options = apply_filters(
'groq_ai_bulk_term_generation_options',
[
'include_top_products' => true,
'top_products_limit' => 10,
],
$term
);
$options['origin'] = $force ? 'term_force_regenerate' : 'term_bulk_auto';
$options['force'] = $force;
$result = $this->run_term_generation( $term, $this->get_term_prompt_text( $term ), $options );
if ( is_wp_error( $result ) ) {
wp_send_json_error( [ 'message' => $result->get_error_message() ], 500 );
}
$settings = $this->plugin->get_settings();
$saved = $this->save_term_generation_result( $term, $result, $settings );
if ( is_wp_error( $saved ) ) {
wp_send_json_error( [ 'message' => $saved->get_error_message() ], 500 );
}
wp_send_json_success(
[
'term_id' => $term_id,
'name' => isset( $term->name ) ? (string) $term->name : '',
'words' => isset( $saved['words'] ) ? absint( $saved['words'] ) : 0,
'count' => isset( $term->count ) ? absint( $term->count ) : 0,
]
);
}
private function run_term_generation( $term, $prompt, $options = [] ) {
if ( ! $term || ! is_object( $term ) ) {
return new WP_Error( 'groq_ai_invalid_term', __( 'Term niet gevonden.', GROQ_AI_PRODUCT_TEXT_DOMAIN ) );
}
$taxonomy = isset( $term->taxonomy ) ? sanitize_key( (string) $term->taxonomy ) : '';
$term_id = isset( $term->term_id ) ? absint( $term->term_id ) : 0;
$options = wp_parse_args(
$options,
[
'include_top_products' => true,
'top_products_limit' => 10,
'origin' => 'term_manual',
'force' => false,
]
);
$origin = isset( $options['origin'] ) ? sanitize_key( (string) $options['origin'] ) : 'term_manual';
$force_run = ! empty( $options['force'] );
$include_top_products = ! empty( $options['include_top_products'] );
$top_products_limit = isset( $options['top_products_limit'] ) ? absint( $options['top_products_limit'] ) : 10;
$top_products_limit = max( 1, min( 25, $top_products_limit ) );
$logger = $this->plugin->get_generation_logger();
$settings = $this->plugin->get_settings();
$provider_manager = $this->plugin->get_provider_manager();
$provider_key = $settings['provider'];
@@ -51,14 +159,13 @@ class Groq_AI_Ajax_Controller {
? $prompt_builder->build_term_system_prompt( $settings, $conversation_id, $term )
: $prompt_builder->build_system_prompt( $settings, $conversation_id );
$model = $this->plugin->get_selected_model( $provider, $settings );
$context_block = '';
if ( method_exists( $prompt_builder, 'build_term_context_block' ) ) {
$context_block = $prompt_builder->build_term_context_block(
$term,
[
'include_top_products' => $include_top_products,
'top_products_limit' => $top_products_limit,
'top_products_limit' => $top_products_limit,
],
$settings
);
@@ -67,6 +174,19 @@ class Groq_AI_Ajax_Controller {
? $prompt_builder->prepend_term_context_to_prompt( $prompt, $context_block )
: $prompt_builder->prepend_context_to_prompt( $prompt, $context_block );
$usage_meta = [
'term_context' => [
'taxonomy' => $taxonomy,
'term_id' => $term_id,
'origin' => $origin,
],
'term_options' => [
'include_top_products' => $include_top_products,
'top_products_limit' => $top_products_limit,
'force' => $force_run,
],
];
$response_format = null;
$use_response_format = $this->plugin->should_use_response_format( $provider, $settings );
if ( $use_response_format && method_exists( $prompt_builder, 'get_term_response_format_definition' ) ) {
@@ -78,6 +198,7 @@ class Groq_AI_Ajax_Controller {
$final_prompt = $prompt_builder->append_response_instructions( $prompt_with_context, $settings );
}
$model = $this->plugin->get_selected_model( $provider, $settings );
$result = $provider->generate_content(
[
'prompt' => $final_prompt,
@@ -91,31 +212,192 @@ class Groq_AI_Ajax_Controller {
);
if ( is_wp_error( $result ) ) {
wp_send_json_error( [ 'message' => $result->get_error_message() ], 500 );
if ( $logger ) {
$logger->log_generation_event(
[
'provider' => $provider_key,
'model' => $model,
'prompt' => $final_prompt,
'response' => '',
'usage' => $usage_meta,
'status' => 'error',
'error_message' => $result->get_error_message(),
'post_id' => 0,
]
);
}
return $result;
}
$response_text = $this->extract_content_text( $result );
$parsed = null;
$response_usage = is_array( $result ) && isset( $result['usage'] ) ? $result['usage'] : [];
if ( ! is_array( $response_usage ) ) {
$response_usage = [];
}
$response_usage['term_context'] = $usage_meta['term_context'];
$response_usage['term_options'] = $usage_meta['term_options'];
$parsed = null;
if ( method_exists( $prompt_builder, 'parse_term_structured_response' ) ) {
$parsed = $prompt_builder->parse_term_structured_response( $response_text, $settings );
}
if ( is_wp_error( $parsed ) ) {
if ( $logger ) {
$logger->log_generation_event(
[
'provider' => $provider_key,
'model' => $model,
'prompt' => $final_prompt,
'response' => $response_text,
'usage' => $response_usage,
'status' => 'error',
'error_message' => $parsed->get_error_message(),
'post_id' => 0,
]
);
}
return $parsed;
}
if ( ! is_array( $parsed ) ) {
$parsed = [
'description' => trim( (string) $response_text ),
];
}
wp_send_json_success(
if ( $logger ) {
$logger->log_generation_event(
[
'provider' => $provider_key,
'model' => $model,
'prompt' => $final_prompt,
'response' => $response_text,
'usage' => $response_usage,
'status' => 'success',
'post_id' => 0,
]
);
}
return [
'top_description' => isset( $parsed['top_description'] ) ? $parsed['top_description'] : ( isset( $parsed['description'] ) ? $parsed['description'] : '' ),
'bottom_description' => isset( $parsed['bottom_description'] ) ? $parsed['bottom_description'] : '',
'meta_title' => isset( $parsed['meta_title'] ) ? $parsed['meta_title'] : '',
'meta_description' => isset( $parsed['meta_description'] ) ? $parsed['meta_description'] : '',
'focus_keywords' => isset( $parsed['focus_keywords'] ) ? $parsed['focus_keywords'] : '',
'description' => isset( $parsed['description'] ) ? $parsed['description'] : ( isset( $parsed['top_description'] ) ? $parsed['top_description'] : '' ),
'raw' => $response_text,
];
}
private function save_term_generation_result( $term, $result, $settings ) {
$term_id = isset( $term->term_id ) ? absint( $term->term_id ) : 0;
$taxonomy = isset( $term->taxonomy ) ? sanitize_key( (string) $term->taxonomy ) : '';
if ( ! $term_id || '' === $taxonomy ) {
return new WP_Error( 'groq_ai_invalid_term', __( 'Term niet gevonden.', GROQ_AI_PRODUCT_TEXT_DOMAIN ) );
}
$top_description = '';
if ( isset( $result['top_description'] ) && '' !== trim( (string) $result['top_description'] ) ) {
$top_description = (string) $result['top_description'];
} elseif ( isset( $result['description'] ) ) {
$top_description = (string) $result['description'];
}
if ( '' === trim( wp_strip_all_tags( $top_description ) ) ) {
return new WP_Error( 'groq_ai_missing_description', __( 'De AI gaf geen omschrijving terug.', GROQ_AI_PRODUCT_TEXT_DOMAIN ) );
}
$update = wp_update_term(
$term_id,
$taxonomy,
[
'top_description' => isset( $parsed['top_description'] ) ? $parsed['top_description'] : ( isset( $parsed['description'] ) ? $parsed['description'] : '' ),
'bottom_description' => isset( $parsed['bottom_description'] ) ? $parsed['bottom_description'] : '',
'meta_title' => isset( $parsed['meta_title'] ) ? $parsed['meta_title'] : '',
'meta_description' => isset( $parsed['meta_description'] ) ? $parsed['meta_description'] : '',
'focus_keywords' => isset( $parsed['focus_keywords'] ) ? $parsed['focus_keywords'] : '',
'description' => isset( $parsed['description'] ) ? $parsed['description'] : ( isset( $parsed['top_description'] ) ? $parsed['top_description'] : '' ),
'raw' => $response_text,
'description' => wp_kses_post( $top_description ),
]
);
if ( is_wp_error( $update ) ) {
return $update;
}
$bottom_key = $this->get_bottom_meta_key( $term, $settings );
if ( '' !== $bottom_key ) {
$bottom_description = isset( $result['bottom_description'] ) ? (string) $result['bottom_description'] : '';
update_term_meta( $term_id, $bottom_key, wp_kses_post( $bottom_description ) );
}
if ( $this->plugin->is_module_enabled( 'rankmath', $settings ) ) {
$rankmath_keys = $this->get_rankmath_term_meta_keys( $term, $settings );
update_term_meta( $term_id, $rankmath_keys['title'], sanitize_text_field( isset( $result['meta_title'] ) ? $result['meta_title'] : '' ) );
update_term_meta( $term_id, $rankmath_keys['description'], sanitize_text_field( isset( $result['meta_description'] ) ? $result['meta_description'] : '' ) );
update_term_meta( $term_id, $rankmath_keys['focus_keyword'], sanitize_text_field( isset( $result['focus_keywords'] ) ? $result['focus_keywords'] : '' ) );
}
return [
'words' => $this->count_words( $top_description ),
];
}
private function get_bottom_meta_key( $term, $settings ) {
$default_key = '';
if ( is_array( $settings ) && isset( $settings['term_bottom_description_meta_key'] ) ) {
$default_key = sanitize_key( (string) $settings['term_bottom_description_meta_key'] );
}
$key = apply_filters( 'groq_ai_term_bottom_description_meta_key', $default_key, $term, $settings );
$key = sanitize_key( (string) $key );
return '' !== $key ? $key : 'groq_ai_term_bottom_description';
}
private function get_rankmath_term_meta_keys( $term, $settings ) {
$defaults = [
'title' => 'rank_math_title',
'description' => 'rank_math_description',
'focus_keyword' => 'rank_math_focus_keyword',
];
$keys = apply_filters( 'groq_ai_rankmath_term_meta_keys', $defaults, $term, $settings );
if ( ! is_array( $keys ) ) {
$keys = $defaults;
}
return [
'title' => isset( $keys['title'] ) ? sanitize_key( (string) $keys['title'] ) : 'rank_math_title',
'description' => isset( $keys['description'] ) ? sanitize_key( (string) $keys['description'] ) : 'rank_math_description',
'focus_keyword' => isset( $keys['focus_keyword'] ) ? sanitize_key( (string) $keys['focus_keyword'] ) : 'rank_math_focus_keyword',
];
}
private function get_term_prompt_text( $term ) {
$prompt = '';
if ( $term && isset( $term->term_id ) ) {
$prompt = (string) get_term_meta( $term->term_id, 'groq_ai_term_custom_prompt', true );
}
$prompt = trim( $prompt );
if ( '' !== $prompt ) {
return $prompt;
}
$default_prompt = __( 'Schrijf een SEO-vriendelijke categorieomschrijving in het Nederlands. Gebruik duidelijke tussenkoppen en <p>-tags. Voeg geen prijsinformatie toe.', GROQ_AI_PRODUCT_TEXT_DOMAIN );
return apply_filters( 'groq_ai_default_term_prompt', $default_prompt, $term );
}
private function count_words( $text ) {
$text = wp_strip_all_tags( (string) $text );
$text = trim( preg_replace( '/\s+/u', ' ', $text ) );
if ( '' === $text ) {
return 0;
}
if ( preg_match_all( '/\pL[\pL\pN\']*/u', $text, $matches ) ) {
return count( $matches[0] );
}
return str_word_count( $text );
}
public function handle_generate_text() {

View File

@@ -537,16 +537,38 @@ class Groq_AI_Prompt_Builder {
$keyword_limit = $this->settings_manager->get_rankmath_focus_keyword_limit( $settings );
$title_pixels = $this->settings_manager->get_rankmath_meta_title_pixel_limit( $settings );
$desc_pixels = $this->settings_manager->get_rankmath_meta_description_pixel_limit( $settings );
$top_char_range = $this->get_char_limit_range_values( $this->settings_manager->get_term_top_description_char_limit( $settings ) );
$bottom_char_range = $this->get_char_limit_range_values( $this->settings_manager->get_term_bottom_description_char_limit( $settings ) );
$top_description_text = __( 'Korte HTML-omschrijving (1 alinea) voor de standaard WordPress term description. Exact één alinea in <p>-tags.', GROQ_AI_PRODUCT_TEXT_DOMAIN );
if ( $top_char_range ) {
$top_description_text .= ' ' . sprintf(
__( 'Doel: ~%1$d tekens (±10%% ⇒ %2$d%3$d).', GROQ_AI_PRODUCT_TEXT_DOMAIN ),
$top_char_range['limit'],
$top_char_range['min'],
$top_char_range['max']
);
}
$bottom_description_text = __( 'Uitgebreide HTML-omschrijving (helemaal onderaan), 24 alineas, met paragrafen en eventueel lijstjes.', GROQ_AI_PRODUCT_TEXT_DOMAIN );
if ( $bottom_char_range ) {
$bottom_description_text .= ' ' . sprintf(
__( 'Doel: ~%1$d tekens (±10%% ⇒ %2$d%3$d).', GROQ_AI_PRODUCT_TEXT_DOMAIN ),
$bottom_char_range['limit'],
$bottom_char_range['min'],
$bottom_char_range['max']
);
}
$properties = [
'top_description' => [
'type' => 'string',
'description' => __( 'Korte HTML-omschrijving (1 alinea) voor de standaard WordPress term description. Exact één alinea in <p>-tags.', GROQ_AI_PRODUCT_TEXT_DOMAIN ),
'description' => $top_description_text,
'minLength' => 20,
],
'bottom_description' => [
'type' => 'string',
'description' => __( 'Uitgebreide HTML-omschrijving (helemaal onderaan), 24 alineas, met paragrafen en eventueel lijstjes.', GROQ_AI_PRODUCT_TEXT_DOMAIN ),
'description' => $bottom_description_text,
'minLength' => 20,
],
];
@@ -675,6 +697,8 @@ class Groq_AI_Prompt_Builder {
'"top_description":"..."',
'"bottom_description":"..."',
];
$top_char_range = $this->get_char_limit_range_values( $this->settings_manager->get_term_top_description_char_limit( $settings ) );
$bottom_char_range = $this->get_char_limit_range_values( $this->settings_manager->get_term_bottom_description_char_limit( $settings ) );
$rankmath_enabled = $this->settings_manager->is_module_enabled( 'rankmath', $settings );
if ( $rankmath_enabled ) {
@@ -693,9 +717,42 @@ class Groq_AI_Prompt_Builder {
$instruction .= ' ' . __( 'Zorg dat top_description en bottom_description geldige HTML bevatten. top_description moet exact één alinea zijn in <p>-tags. bottom_description moet 24 alineas bevatten.', GROQ_AI_PRODUCT_TEXT_DOMAIN );
$instruction .= ' ' . __( 'Voeg geen extra tekst buiten het JSON-object toe.', GROQ_AI_PRODUCT_TEXT_DOMAIN );
$instruction .= ' ' . __( 'Als in de context een sectie "Interne links" staat, verwerk dan 25 van deze links natuurlijk in bottom_description als HTML-links (<a href="URL">Anker</a>).', GROQ_AI_PRODUCT_TEXT_DOMAIN );
if ( $top_char_range ) {
$instruction .= ' ' . sprintf(
__( 'Houd top_description rond %1$d tekens en blijf tussen %2$d en %3$d tekens (±10%% marge).', GROQ_AI_PRODUCT_TEXT_DOMAIN ),
$top_char_range['limit'],
$top_char_range['min'],
$top_char_range['max']
);
}
if ( $bottom_char_range ) {
$instruction .= ' ' . sprintf(
__( 'Houd bottom_description rond %1$d tekens en blijf tussen %2$d en %3$d tekens (±10%% marge).', GROQ_AI_PRODUCT_TEXT_DOMAIN ),
$bottom_char_range['limit'],
$bottom_char_range['min'],
$bottom_char_range['max']
);
}
return $instruction;
}
private function get_char_limit_range_values( $limit ) {
$limit = absint( $limit );
if ( $limit <= 0 ) {
return null;
}
$min = (int) floor( $limit * 0.9 );
$max = (int) ceil( $limit * 1.1 );
return [
'limit' => $limit,
'min' => max( 1, $min ),
'max' => max( $min, $max ),
];
}
private function resolve_term_bottom_description_meta_key( $term = null, $settings = null ) {
$default_key = '';
if ( is_array( $settings ) && isset( $settings['term_bottom_description_meta_key'] ) ) {
@@ -716,9 +773,15 @@ class Groq_AI_Prompt_Builder {
'post_status' => 'publish',
'posts_per_page' => $limit,
'no_found_rows' => true,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => [
[
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
],
],
'tax_query' => [
[
'taxonomy' => $taxonomy,

View File

@@ -52,6 +52,8 @@ class Groq_AI_Settings_Manager {
'image_context_mode' => 'url',
'image_context_limit' => 3,
'response_format_compat' => false,
'term_top_description_char_limit' => 600,
'term_bottom_description_char_limit' => 1200,
];
$settings = get_option( $this->option_key, [] );
@@ -79,6 +81,15 @@ class Groq_AI_Settings_Manager {
isset( $settings['product_attribute_includes'] ) ? $settings['product_attribute_includes'] : []
);
$settings['term_top_description_char_limit'] = $this->sanitize_term_description_char_limit_value(
isset( $settings['term_top_description_char_limit'] ) ? $settings['term_top_description_char_limit'] : $defaults['term_top_description_char_limit'],
$defaults['term_top_description_char_limit']
);
$settings['term_bottom_description_char_limit'] = $this->sanitize_term_description_char_limit_value(
isset( $settings['term_bottom_description_char_limit'] ) ? $settings['term_bottom_description_char_limit'] : $defaults['term_bottom_description_char_limit'],
$defaults['term_bottom_description_char_limit']
);
return $settings;
}
@@ -114,6 +125,8 @@ class Groq_AI_Settings_Manager {
'image_context_mode' => 'url',
'image_context_limit' => 3,
'response_format_compat' => false,
'term_top_description_char_limit' => 600,
'term_bottom_description_char_limit' => 1200,
];
$current_settings = $this->all();
@@ -151,6 +164,15 @@ class Groq_AI_Settings_Manager {
$context_fields['images'] = true;
}
$top_char_limit = $this->sanitize_term_description_char_limit_value(
isset( $raw_input['term_top_description_char_limit'] ) ? $raw_input['term_top_description_char_limit'] : $defaults['term_top_description_char_limit'],
$defaults['term_top_description_char_limit']
);
$bottom_char_limit = $this->sanitize_term_description_char_limit_value(
isset( $raw_input['term_bottom_description_char_limit'] ) ? $raw_input['term_bottom_description_char_limit'] : $defaults['term_bottom_description_char_limit'],
$defaults['term_bottom_description_char_limit']
);
return [
'provider' => $provider,
'model' => $model,
@@ -174,6 +196,8 @@ class Groq_AI_Settings_Manager {
'response_format_compat' => ! empty( $raw_input['response_format_compat'] ),
'image_context_mode' => $image_mode,
'image_context_limit' => $image_limit,
'term_top_description_char_limit' => $top_char_limit,
'term_bottom_description_char_limit' => $bottom_char_limit,
'context_fields' => $context_fields,
'modules' => $this->sanitize_modules_settings(
$modules_posted ? $raw_input['modules'] : [],
@@ -211,6 +235,22 @@ class Groq_AI_Settings_Manager {
return $clean;
}
private function sanitize_term_description_char_limit_value( $value, $default ) {
$default_value = absint( $default ) > 0 ? absint( $default ) : 600;
if ( null === $value || '' === $value ) {
$value = $default_value;
}
$value = absint( $value );
if ( $value <= 0 ) {
$value = $default_value;
}
return max( 100, min( 5000, $value ) );
}
public function get_context_field_definitions() {
if ( null === $this->context_field_definitions ) {
$this->context_field_definitions = [
@@ -362,6 +402,26 @@ class Groq_AI_Settings_Manager {
return $this->sanitize_image_context_limit_value( $limit );
}
public function get_term_top_description_char_limit( $settings = null ) {
if ( null === $settings ) {
$settings = $this->all();
}
$value = isset( $settings['term_top_description_char_limit'] ) ? $settings['term_top_description_char_limit'] : 600;
return $this->sanitize_term_description_char_limit_value( $value, 600 );
}
public function get_term_bottom_description_char_limit( $settings = null ) {
if ( null === $settings ) {
$settings = $this->all();
}
$value = isset( $settings['term_bottom_description_char_limit'] ) ? $settings['term_bottom_description_char_limit'] : 1200;
return $this->sanitize_term_description_char_limit_value( $value, 1200 );
}
public function is_response_format_compat_enabled( $settings = null ) {
if ( null === $settings ) {
$settings = $this->all();