$post_id, 'tone' => $tone ) );
$messages = array(
array(
'role' => 'system',
'content' => 'You are a professional product description writer for an e-commerce store. '
. $tone_instruction . ' '
. 'STRICT OUTPUT RULES: '
. '(1) Never use markdown, code fences (```), or backticks anywhere in your response. '
. '(2) The [EXCERPT] section must be plain text only — no HTML tags. '
. '(3) The [DESCRIPTION] section must use raw HTML tags (
,
, - , etc.) directly — never wrapped in a code block. '
. '(4) Output nothing outside the [EXCERPT] and [DESCRIPTION] sections. '
. self::product_facts_rules(),
),
array(
'role' => 'user',
'content' => "Write a product excerpt and a full description for this product.\n\n"
. "Product details:\n" . $context . "\n\n"
. "Use exactly this format and nothing else:\n"
. "[EXCERPT]\n"
. "2-3 sentences of plain text. No HTML here.\n"
. "[DESCRIPTION]\n"
. "Full product description using raw HTML (
,
, - , ). No code fences.",
),
);
$data = self::call_chat_api( $messages, 600, 1.0, 'description' );
if ( is_wp_error( $data ) ) {
return $data;
}
// Strip any code fences the model may have added around the whole response.
$content = self::strip_code_fences( $data['choices'][0]['message']['content'] );
preg_match( '/\[EXCERPT\](.*?)\[DESCRIPTION\](.*)/s', $content, $matches );
$raw_description = isset( $matches[2] ) ? trim( $matches[2] ) : $content;
$raw_excerpt = isset( $matches[1] ) ? trim( $matches[1] ) : '';
// Strip any code fences that may have wrapped each section individually.
$raw_description = self::strip_code_fences( $raw_description );
// Excerpt must be plain text — strip any HTML tags the model snuck in.
$raw_excerpt = wp_strip_all_tags( self::strip_code_fences( $raw_excerpt ) );
return array(
'description' => wp_kses_post( $raw_description ),
'excerpt' => sanitize_textarea_field( $raw_excerpt ),
);
}
/**
* Generates a short product description via ChatGPT.
*
* @param int $post_id
* @param string $tone
* @return string|WP_Error
*/
public static function api_generate_short_description( $post_id, $tone = 'formal' ) {
$product = wc_get_product( absint( $post_id ) );
if ( ! $product ) {
return new WP_Error( 'invalid_product', __( 'Invalid product ID.', 'ai-content-generator-for-woocommerce' ) );
}
$context = self::build_product_context( $product );
$tone_map = array(
'formal' => 'Use a professional and business-like tone.',
'casual' => 'Use a friendly, conversational tone.',
'persuasive' => 'Use a compelling, sales-focused tone.',
'technical' => 'Focus on technical specifications and features.',
'luxury' => 'Emphasize premium quality and exclusivity.',
'creative' => 'Use creative and engaging language.',
);
$tone_note = $tone_map[ $tone ] ?? $tone_map['formal'];
$messages = array(
array(
'role' => 'system',
'content' => 'You are a professional e-commerce copywriter. '
. 'Write exactly 2-3 plain text sentences. '
. 'STRICT OUTPUT RULES: No HTML tags. No markdown. No code fences (```). No bullet points. No labels or headings. Plain sentences only. '
. self::product_facts_rules(),
),
array(
'role' => 'user',
'content' => "Write a short product description (2-3 plain text sentences) for this product. $tone_note\n\n"
. "Product details:\n" . $context,
),
);
$data = self::call_chat_api( $messages, 150, 1.0, 'short_description' );
if ( is_wp_error( $data ) ) {
return $data;
}
$clean = self::clean_plain_text( $data['choices'][0]['message']['content'] );
return wpautop( $clean );
}
/**
* Product facts for the description prompts: name, categories, brand,
* tags, attributes, price, weight, dimensions and the current copy.
*
* @param WC_Product $product
* @return string One "Label: value" line per known fact.
*/
private static function build_product_context( $product ) {
$product_id = $product->get_id();
$lines = array( 'Product name: ' . $product->get_name() );
$taxonomies = array(
'product_cat' => 'Categories',
'product_brand' => 'Brand',
'product_tag' => 'Tags',
);
foreach ( $taxonomies as $taxonomy => $label ) {
if ( ! taxonomy_exists( $taxonomy ) ) {
continue;
}
// Cached terms, filtered here rather than with an "exclude" query argument.
$terms = get_the_terms( $product_id, $taxonomy );
if ( ! is_array( $terms ) ) {
continue;
}
if ( 'product_cat' === $taxonomy ) {
// "Uncategorized" tells the AI nothing.
$default_cat = (int) get_option( 'default_product_cat', 0 );
$terms = array_filter( $terms, static function ( $term ) use ( $default_cat ) {
return $term->term_id !== $default_cat;
} );
}
if ( ! empty( $terms ) ) {
$lines[] = $label . ': ' . wp_specialchars_decode( implode( ', ', wp_list_pluck( $terms, 'name' ) ), ENT_QUOTES );
}
}
foreach ( $product->get_attributes() as $attribute ) {
if ( ! $attribute instanceof WC_Product_Attribute ) {
continue;
}
$values = $attribute->is_taxonomy()
? wc_get_product_terms( $product_id, $attribute->get_name(), array( 'fields' => 'names' ) )
: $attribute->get_options();
if ( ! empty( $values ) ) {
$lines[] = wc_attribute_label( $attribute->get_name(), $product ) . ': ' . wp_specialchars_decode( implode( ', ', $values ), ENT_QUOTES );
}
}
if ( $product->is_type( 'variable' ) ) {
$min = $product->get_variation_price( 'min' );
$max = $product->get_variation_price( 'max' );
$price = $min === $max ? $min : $min . ' – ' . $max;
} else {
$price = $product->get_price();
}
if ( (float) $price > 0 ) {
$lines[] = 'Price: ' . $price . ' ' . get_woocommerce_currency();
}
if ( '' !== (string) $product->get_weight() ) {
$lines[] = 'Weight: ' . $product->get_weight() . ' ' . get_option( 'woocommerce_weight_unit' );
}
if ( $product->has_dimensions() ) {
$lines[] = 'Dimensions: ' . html_entity_decode( wc_format_dimensions( $product->get_dimensions( false ) ), ENT_QUOTES, 'UTF-8' );
}
$short_description = trim( wp_strip_all_tags( $product->get_short_description() ) );
$description = trim( wp_strip_all_tags( $product->get_description() ) );
if ( '' !== $short_description ) {
$lines[] = 'Current short description: ' . wp_html_excerpt( $short_description, 600, '…' );
}
if ( '' !== $description ) {
$lines[] = 'Current description: ' . wp_html_excerpt( $description, 1200, '…' );
}
return implode( "\n", $lines );
}
/**
* Shared prompt rule: stick to the facts from build_product_context().
*
* @return string
*/
private static function product_facts_rules() {
return 'Use only the facts in the product details. Never invent specifications, materials, dimensions, '
. 'certifications, awards or reviews. The price is for positioning only: never state it. '
. 'When a current description is given, keep its facts but write fresh copy.';
}
/**
* Generates SEO-friendly product name (title) suggestions via the AI chat API.
*
* Uses the product's title (preferring the live, possibly-unsaved value from
* the editor field over the saved post title), short description,
* description, and categories as context so the AI refines the existing
* name rather than inventing one out of nothing.
*
* @param int $post_id Product ID.
* @param string $current_name Live value of the Product Name field (may be unsaved). Optional.
* @return array{ titles: string[] }|WP_Error
*/
public static function api_generate_product_title( $post_id, $current_name = '' ) {
$product = wc_get_product( absint( $post_id ) );
if ( ! $product ) {
return new WP_Error( 'invalid_product', __( 'Invalid product ID.', 'ai-content-generator-for-woocommerce' ) );
}
// Prefer the live (possibly unsaved) field value over the saved post title.
$title = '' !== trim( $current_name ) ? trim( $current_name ) : $product->get_name();
if ( '' === trim( $title ) ) {
return new WP_Error( 'missing_title', __( 'Please enter a product name first — the AI needs it as a starting point to suggest SEO-friendly alternatives.', 'ai-content-generator-for-woocommerce' ) );
}
self::log_debug( 'Generating product title', array( 'post_id' => $post_id, 'title' => $title ) );
$short_description = $product->get_short_description();
$description = $product->get_description();
$categories = wp_get_post_terms( absint( $post_id ), 'product_cat', array( 'fields' => 'names' ) );
$prompt = "Based on the following product information, suggest 5 SEO-friendly, optimized product name/title alternatives. ";
$prompt .= "Current Product Title: $title. ";
if ( ! empty( $short_description ) ) { $prompt .= 'Short Description: ' . wp_strip_all_tags( $short_description ) . '. '; }
if ( ! empty( $description ) ) { $prompt .= 'Description: ' . wp_strip_all_tags( $description ) . '. '; }
if ( ! empty( $categories ) ) { $prompt .= 'Categories: ' . implode( ', ', $categories ) . '. '; }
$prompt .= 'Each title must: be highly relevant to the product, include the most important keywords a shopper would search for, '
. 'stay close to a standard SEO length of around 50-60 characters (never exceed 70), avoid keyword stuffing, avoid special characters like | or -, '
. 'not include quotation marks, and read naturally as a real product name. '
. 'Return only the 5 titles, one per line, without any numbering, bullets, labels, or additional formatting.';
$messages = array(
array(
'role' => 'system',
'content' => 'You are an e-commerce SEO copywriter who specializes in writing high-converting, keyword-optimized product titles for online stores.',
),
array( 'role' => 'user', 'content' => $prompt ),
);
$data = self::call_chat_api( $messages, 2000, 1.0, 'title' );
if ( is_wp_error( $data ) ) {
return $data;
}
$raw = array_filter( array_map( 'trim', explode( "\n", trim( $data['choices'][0]['message']['content'] ) ) ) );
$titles = array_values( array_filter( array_map( function ( $t ) {
$t = preg_replace( '/^\d+[\.\)\-\s]*\s*/', '', $t ); // Strip leading numbering.
$t = trim( $t, " \t\n\r\0\x0B\"'" ); // Strip stray quotes.
return sanitize_text_field( $t );
}, $raw ) ) );
self::log_debug( 'Cleaned product titles', array( 'titles' => $titles ) );
return array( 'titles' => $titles );
}
/**
* Generates brand suggestions via ChatGPT.
*
* @param int $post_id
* @return array{ brands: string[] }|WP_Error
*/
public static function api_generate_brands( $post_id ) {
$product = wc_get_product( absint( $post_id ) );
if ( ! $product ) {
return new WP_Error( 'invalid_product', __( 'Invalid product ID.', 'ai-content-generator-for-woocommerce' ) );
}
self::log_debug( 'Generating product brands', array( 'post_id' => $post_id, 'title' => $product->get_name() ) );
$title = $product->get_name();
$short_description = $product->get_short_description();
$description = $product->get_description();
$categories = wp_get_post_terms( absint( $post_id ), 'product_cat', array( 'fields' => 'names' ) );
$prompt = "Based on the following product information, suggest 3-5 relevant brand names that would be appropriate for this product. ";
$prompt .= "Product Title: $title. ";
if ( ! empty( $short_description ) ) { $prompt .= 'Short Description: ' . wp_strip_all_tags( $short_description ) . '. '; }
if ( ! empty( $description ) ) { $prompt .= 'Description: ' . wp_strip_all_tags( $description ) . '. '; }
if ( ! empty( $categories ) ) { $prompt .= 'Categories: ' . implode( ', ', $categories ) . '. '; }
$prompt .= 'Return only the brand names, one per line, without any numbering, bullets, or additional formatting. Just the brand names.';
$messages = array(
array( 'role' => 'system', 'content' => 'You are a product branding expert. Provide relevant brand suggestions based on product details.' ),
array( 'role' => 'user', 'content' => $prompt ),
);
$data = self::call_chat_api( $messages, 200, 1.0, 'brands' );
if ( is_wp_error( $data ) ) {
return $data;
}
$raw = array_filter( array_map( 'trim', explode( "\n", trim( $data['choices'][0]['message']['content'] ) ) ) );
$brands = array_values( array_filter( array_map( function ( $b ) {
return trim( preg_replace( '/^\d+[\.\)\-\s]*\s*/', '', $b ) );
}, $raw ) ) );
self::log_debug( 'Cleaned brands', array( 'brands' => $brands ) );
return array( 'brands' => $brands );
}
/**
* Generates product tags via ChatGPT.
*
* @param int $post_id
* @return array{ tags: string[] }|WP_Error
*/
public static function api_generate_tags( $post_id ) {
$product = wc_get_product( absint( $post_id ) );
if ( ! $product ) {
return new WP_Error( 'invalid_product', __( 'Invalid product ID.', 'ai-content-generator-for-woocommerce' ) );
}
self::log_debug( 'Generating product tags', array( 'post_id' => $post_id, 'title' => $product->get_name() ) );
$title = $product->get_name();
$short_description = $product->get_short_description();
$description = $product->get_description();
$categories = wp_get_post_terms( absint( $post_id ), 'product_cat', array( 'fields' => 'names' ) );
$prompt = "Based on the following product information, suggest 8-12 relevant tags/keywords that would be appropriate for this product. ";
$prompt .= "Product Title: $title. ";
if ( ! empty( $short_description ) ) { $prompt .= 'Short Description: ' . wp_strip_all_tags( $short_description ) . '. '; }
if ( ! empty( $description ) ) { $prompt .= 'Description: ' . wp_strip_all_tags( $description ) . '. '; }
if ( ! empty( $categories ) ) { $prompt .= 'Categories: ' . implode( ', ', $categories ) . '. '; }
$prompt .= 'Return only the tags, separated by commas, without any additional text or formatting.';
$messages = array(
array( 'role' => 'system', 'content' => 'You are a product tagging expert. Provide relevant tags and keywords based on product details for better searchability.' ),
array( 'role' => 'user', 'content' => $prompt ),
);
$data = self::call_chat_api( $messages, 300, 1.0, 'tags' );
if ( is_wp_error( $data ) ) {
return $data;
}
$tags = array_values( array_filter( array_map( 'trim', explode( ',', trim( $data['choices'][0]['message']['content'] ) ) ) ) );
return array( 'tags' => $tags );
}
}