' . __( 'Settings', 'ai-content-generator-for-woocommerce' ) . '',
'' . __( 'User Guide', 'ai-content-generator-for-woocommerce' ) . '',
'' . __( 'Support', 'ai-content-generator-for-woocommerce' ) . '',
'' . __( 'Review', 'ai-content-generator-for-woocommerce' ) . '',
);
return array_merge( $custom_links, $links );
}
/**
* Redirects once, right after the plugin is activated: to the setup wizard
* while no provider is connected, otherwise to the settings page.
* Skipped for bulk/network activations, AJAX, WP-CLI, and users who can't
* access the page.
*/
public function maybe_redirect_after_activation() {
if ( ! get_transient( 'wtofe_ai_activation_redirect' ) ) {
return;
}
delete_transient( 'wtofe_ai_activation_redirect' );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only check of core's bulk-activate flag.
if ( wp_doing_ajax() || is_network_admin() || isset( $_GET['activate-multi'] )
|| ( defined( 'WP_CLI' ) && WP_CLI )
|| ! class_exists( 'WooCommerce' )
|| ! current_user_can( 'manage_woocommerce' ) ) {
return;
}
wp_safe_redirect( WTOFE_Setup_Wizard::should_redirect()
? WTOFE_Setup_Wizard::get_url()
: admin_url( 'admin.php?page=wc-ai-content-generator' ) );
exit;
}
/**
* Registers plugin settings fields.
*/
public function register_settings() {
register_setting( 'wc_product_image_generator', 'wtofe_chatgpt_api_key', array(
'type' => 'string',
'sanitize_callback' => array( $this, 'sanitize_chatgpt_api_key' ),
) );
register_setting( 'wc_product_image_generator', 'wtofe_use_custom_api_key', array(
'type' => 'boolean',
'default' => false,
'sanitize_callback' => 'rest_sanitize_boolean',
) );
register_setting( 'wc_product_image_generator', 'wtofe_ai_debug_mode', array(
'type' => 'boolean',
'default' => false,
'sanitize_callback' => 'rest_sanitize_boolean',
) );
register_setting( 'wc_product_image_generator', 'wtofe_ai_badge_enabled', array(
'type' => 'boolean',
'default' => false,
'sanitize_callback' => 'rest_sanitize_boolean',
) );
register_setting( 'wc_product_image_generator', 'wtofe_ai_badge_message', array(
'type' => 'string',
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
) );
// AI Model & Generation Settings.
$model_features = array( 'description', 'short_description', 'title', 'brands', 'tags' );
$token_defaults = array(
'description' => 4000,
'short_description' => 2000,
'title' => 2000,
'brands' => 500,
'tags' => 500,
);
foreach ( $model_features as $feature ) {
register_setting( 'wc_product_image_generator', 'wtofe_ai_model_' . $feature, array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
) );
register_setting( 'wc_product_image_generator', 'wtofe_ai_max_tokens_' . $feature, array(
'type' => 'integer',
'sanitize_callback' => function( $val ) use ( $feature, $token_defaults ) {
$val = absint( $val );
if ( $val < 50 ) {
$default = $token_defaults[ $feature ];
add_settings_error(
'wtofe_ai_max_tokens_' . $feature,
'wtofe_tokens_reset_' . $feature,
sprintf(
/* translators: 1: feature name, 2: default token count */
__( 'Max Tokens for "%1$s" was below the minimum (50) and has been reset to the default (%2$d).', 'ai-content-generator-for-woocommerce' ),
$feature,
$default
),
'warning'
);
return $default;
}
return $val;
},
) );
register_setting( 'wc_product_image_generator', 'wtofe_ai_temperature_' . $feature, array(
'type' => 'number',
'sanitize_callback' => function( $val ) { return min( 2.0, max( 0.0, (float) $val ) ); },
) );
// Image generation model setting.
register_setting( 'wc_product_image_generator', 'wtofe_ai_model_image_generation', array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
) );
}
register_setting( 'wc_product_image_generator', 'wtofe_ai_request_timeout', array(
'type' => 'integer',
'default' => 30,
'sanitize_callback' => 'absint',
) );
}
/**
* Checks an API key's format, then confirms it with a live OpenAI /v1/models
* call. Shared by the inline "Validate & Save" AJAX action and the
* pre-submit validation used when saving via the main settings form.
*
* @param string $api_key
* @return string Empty string if valid, otherwise a user-facing error message.
*/
private function get_api_key_validation_error( $api_key ) {
if ( ! preg_match( '/^sk-[A-Za-z0-9_-]{20,}$/', $api_key ) ) {
return __( 'The API key doesn\'t appear to be in a valid format. Please check that you copied the complete key and try again.', 'ai-content-generator-for-woocommerce' );
}
$response = wp_remote_get( 'https://api.openai.com/v1/models', array( //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration
'headers' => array(
'Authorization' => 'Bearer ' . $api_key,
),
'timeout' => 15,
) );
if ( is_wp_error( $response ) ) {
return __( 'Could not reach OpenAI to verify the key. Please check your connection and try again.', 'ai-content-generator-for-woocommerce' );
}
if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
return __( 'OpenAI rejected this API key. Please double-check it and try again.', 'ai-content-generator-for-woocommerce' );
}
return '';
}
/**
* AJAX handler used by the settings page to validate a new custom API key
* before the form is actually submitted, so an invalid key can be reported
* inline (in red, under the field) without a full page reload.
*
* Checks the key's format first, then confirms it's actually accepted by
* OpenAI via a lightweight GET to /v1/models (cheap, no completion cost).
*/
public function ajax_validate_api_key() {
check_ajax_referer( 'wtofe_validate_api_key', 'nonce' );
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-content-generator-for-woocommerce' ) ) );
}
$api_key = isset( $_POST['api_key'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) ) : '';
$error = $this->get_api_key_validation_error( $api_key );
if ( $error ) {
wp_send_json_error( array( 'message' => $error ) );
}
wp_send_json_success();
}
/**
* AJAX handler for the "Validate & Save API Key" button: validates the key
* exactly like ajax_validate_api_key(), and — only once confirmed working —
* saves it immediately, independent of the main settings form submission.
* Returns the masked value so the field can be updated in place.
*/
public function ajax_save_api_key() {
check_ajax_referer( 'wtofe_save_api_key', 'nonce' );
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-content-generator-for-woocommerce' ) ) );
}
$api_key = isset( $_POST['api_key'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) ) : '';
$error = $this->get_api_key_validation_error( $api_key );
if ( $error ) {
wp_send_json_error( array( 'message' => $error ) );
}
update_option( 'wtofe_chatgpt_api_key', $api_key );
// The setup wizard also switches "Use Custom ChatGPT API Key" on, since
// it has no separate toggle.
if ( ! empty( $_POST['enable'] ) ) {
update_option( 'wtofe_use_custom_api_key', true );
}
wp_send_json_success( array(
'message' => __( 'API key validated and saved successfully.', 'ai-content-generator-for-woocommerce' ),
'masked' => self::mask_provider_api_key( $api_key ),
) );
}
/**
* Sanitizes and validates the OpenAI API key on save.
*
* The field is left blank in the UI once a key is already saved (it shows a
* masked display instead), so an empty submission means "unchanged" and the
* existing key is preserved. A non-empty submission is checked against the
* expected OpenAI secret-key format; invalid input is rejected (old key kept)
* and a settings error is shown to the user.
*
* @param string $value Raw posted value.
* @return string
*/
public function sanitize_chatgpt_api_key( $value ) {
$value = trim( sanitize_text_field( (string) $value ) );
$existing = get_option( 'wtofe_chatgpt_api_key', '' );
// Blank submission — field wasn't touched, keep the existing key.
if ( '' === $value ) {
return $existing;
}
// OpenAI secret keys start with "sk-" and are long alphanumeric/underscore/hyphen strings.
if ( ! preg_match( '/^sk-[A-Za-z0-9_-]{20,}$/', $value ) ) {
add_settings_error(
'wtofe_chatgpt_api_key',
'wtofe_invalid_api_key',
__( 'The API key doesn\'t appear to be in a valid format. Please check that you copied the complete key and try again.', 'ai-content-generator-for-woocommerce' ),
'error'
);
return $existing;
}
add_settings_error(
'wtofe_chatgpt_api_key',
'wtofe_api_key_updated',
__( 'API key updated successfully.', 'ai-content-generator-for-woocommerce' ),
'updated'
);
return $value;
}
/**
* AJAX handler for the "Remove" button next to the custom API key field.
* Deletes the wtofe_chatgpt_api_key option outright (not just sets it blank),
* independent of the Settings API save cycle so it can't be re-added.
*/
public function ajax_remove_api_key() {
check_ajax_referer( 'wtofe_remove_api_key', 'nonce' );
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-content-generator-for-woocommerce' ) ) );
}
delete_option( 'wtofe_chatgpt_api_key' );
wp_send_json_success();
}
/**
* AJAX: lists the connection tests to run (labels and IDs only, no keys).
* The browser then runs each one in parallel via ajax_run_connection_test(),
* so one slow provider can't hold up the others or the PHP time limit.
*/
public function ajax_list_connection_tests() {
check_ajax_referer( 'wtofe_test_connection', 'nonce' );
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-content-generator-for-woocommerce' ) ) );
}
$tests = AI_Content_Generator_For_WooCommerce_Helper::get_connection_tests();
if ( empty( $tests ) ) {
wp_send_json_error( array( 'message' => __( 'No AI provider is configured yet. Add an API key or connect a provider, save, then test again.', 'ai-content-generator-for-woocommerce' ) ) );
}
wp_send_json_success( array( 'tests' => $tests ) );
}
/** AJAX: runs one connection test and returns the explained result. */
public function ajax_run_connection_test() {
check_ajax_referer( 'wtofe_test_connection', 'nonce' );
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-content-generator-for-woocommerce' ) ) );
}
$test_id = isset( $_POST['test'] ) ? sanitize_key( wp_unslash( $_POST['test'] ) ) : '';
$result = AI_Content_Generator_For_WooCommerce_Helper::run_connection_test( $test_id );
if ( is_wp_error( $result ) ) {
wp_send_json_error( array( 'message' => $result->get_error_message() ) );
}
wp_send_json_success( $result );
}
/**
* Masks a connector/provider API key for display in the AI Plugin
* connectors tiles: keeps the first 10 characters and the last 4,
* replacing the middle with bullet characters.
*
* @param string $key
* @return string
*/
public static function mask_provider_api_key( $key ) {
$key = trim( (string) $key );
$len = strlen( $key );
if ( '' === $key ) {
return '';
}
if ( $len <= 14 ) {
return str_repeat( '•', max( 4, $len ) );
}
$prefix = substr( $key, 0, 10 );
$suffix = substr( $key, -4 );
return $prefix . str_repeat( '•', 20 ) . $suffix;
}
/**
* Shows an admin notice on every admin screen while no AI provider is
* connected (no AI Connector key and no custom ChatGPT API key), linking
* to the setup wizard. It goes away on its own once a provider is
* connected. Skipped on Settings > Connectors, where the user is already
* connecting one.
*/
public function maybe_render_connector_notice() {
if ( ! current_user_can( 'manage_woocommerce' )
|| self::is_connectors_screen()
|| AI_Content_Generator_For_WooCommerce_Helper::has_active_connector() ) {
return;
}
?>
Connectors" screen.
*
* @return bool
*/
private static function is_connectors_screen() {
$screen = get_current_screen();
if ( $screen && 'settings_page_options-connectors' === $screen->id ) {
return true;
}
// Fall back to checking the request directly, since the Connectors
// screen is a newer core screen and its $screen->id may vary.
return ! empty( $GLOBALS['pagenow'] ) && 'options-connectors.php' === $GLOBALS['pagenow'];
}
/**
* Adds a small notice on the WordPress "Settings > Connectors" screen
* linking back to this plugin's settings page, so admins can find their
* way back after connecting a provider.
*/
public function maybe_render_plugin_link_on_connectors_page() {
if ( ! self::is_connectors_screen() ) {
return;
}
$settings_url = admin_url( 'admin.php?page=wc-ai-content-generator' );
?>
' . esc_html__( 'AI Content Generator settings', 'ai-content-generator-for-woocommerce' ) . ''
)
);
?>
ID );
require WTOFE_AI_PLUGIN_DIR . 'admin/partials/meta-box-featured-image.php';
}
/** Renders the gallery image meta box. */
public function gallery_image_meta_box_callback( $post ) {
$post_id = absint( $post->ID );
require WTOFE_AI_PLUGIN_DIR . 'admin/partials/meta-box-gallery-image.php';
}
/** Renders the AI-generated status meta box. */
public function ai_status_meta_box_callback( $post ) {
$post_id = absint( $post->ID );
require WTOFE_AI_PLUGIN_DIR . 'admin/partials/meta-box-ai-status.php';
}
// -------------------------------------------------------------------------
// Scripts & Inline Loaders
// -------------------------------------------------------------------------
/**
* Strings for the "Test connection" results. Shared by the setup wizard's
* script below and the settings app (WTOFE_Settings_App_Sections).
*
* @return array
*/
public static function get_connection_test_i18n() {
return array(
'testing' => __( 'Testing…', 'ai-content-generator-for-woocommerce' ),
'checking' => __( 'Checking…', 'ai-content-generator-for-woocommerce' ),
'connected' => __( 'Connected', 'ai-content-generator-for-woocommerce' ),
/* translators: %s: comma-separated feature names */
'usedFor' => __( 'Used for: %s', 'ai-content-generator-for-woocommerce' ),
'notUsed' => __( 'Not used by any feature yet', 'ai-content-generator-for-woocommerce' ),
/* translators: %s: provider name, e.g. OpenAI */
'providerSaid' => __( '%s said:', 'ai-content-generator-for-woocommerce' ),
'failed' => __( 'Test failed', 'ai-content-generator-for-woocommerce' ),
'requestFailed' => __( 'Your server didn\'t finish the test. It may have stopped the request before the provider replied. Try again, or lower the request timeout.', 'ai-content-generator-for-woocommerce' ),
'listFailed' => __( 'Could not start the connection test. Reload the page and try again.', 'ai-content-generator-for-woocommerce' ),
);
}
/**
* Enqueues the "Test connection" script and styles used by the setup
* wizard. Its fix links open the settings page at the field to change.
*/
public static function enqueue_connection_test_script() {
wp_enqueue_style(
'wtofe-connection-test',
WTOFE_AI_PLUGIN_URL . 'admin/css/connection-test.css',
array(),
WTOFE_AI_VERSION
);
wp_enqueue_script(
'wtofe-connection-test',
WTOFE_AI_PLUGIN_URL . 'admin/js/connection-test.js',
array( 'jquery' ),
WTOFE_AI_VERSION,
true
);
wp_localize_script( 'wtofe-connection-test', 'wtofeConnTest', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wtofe_test_connection' ),
// Fix links point at settings-page fields; off that page they open it.
'settingsUrl' => admin_url( 'admin.php?page=wc-ai-content-generator' ),
'i18n' => self::get_connection_test_i18n(),
) );
}
/** Enqueues admin CSS and JS on product edit screens. */
public function enqueue_scripts( $hook ) {
if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
return;
}
$screen = get_current_screen();
if ( ! $screen || 'product' !== $screen->post_type ) {
return;
}
wp_enqueue_style(
'wc-product-description-generator',
WTOFE_AI_PLUGIN_URL . 'admin/css/description-generator.css',
array(),
WTOFE_AI_VERSION
);
wp_enqueue_script(
'wc-product-description-generator',
WTOFE_AI_PLUGIN_URL . 'admin/js/description-generator.js',
array( 'jquery', 'wp-editor' ),
WTOFE_AI_VERSION,
true
);
wp_localize_script( 'wc-product-description-generator', 'wcProdDescGen', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wc_product_image_generator_nonce' ),
'postId' => get_the_ID(),
'generateDesc' => __( 'Generate Description', 'ai-content-generator-for-woocommerce' ),
'generateShortDesc'=> __( 'Generate Short Description', 'ai-content-generator-for-woocommerce' ),
'generateTitle' => __( 'Generate Product Name', 'ai-content-generator-for-woocommerce' ),
'generatingTitle' => __( 'Generating product name suggestions...', 'ai-content-generator-for-woocommerce' ),
'generateMoreTitles' => __( 'Generate More', 'ai-content-generator-for-woocommerce' ),
'useThisTitle' => __( 'Use This', 'ai-content-generator-for-woocommerce' ),
'generateBrands' => __( 'Generate Brands', 'ai-content-generator-for-woocommerce' ),
'generateTags' => __( 'Generate Tags', 'ai-content-generator-for-woocommerce' ),
'generatingBrands' => __( 'Generating brands...', 'ai-content-generator-for-woocommerce' ),
'generatingTags' => __( 'Generating tags...', 'ai-content-generator-for-woocommerce' ),
'applyBrands' => __( 'Apply Brands', 'ai-content-generator-for-woocommerce' ),
'applyTags' => __( 'Apply Tags', 'ai-content-generator-for-woocommerce' ),
'generateMoreBrands'=> __( 'Generate More Brands', 'ai-content-generator-for-woocommerce' ),
'generateMoreTags' => __( 'Generate More Tags', 'ai-content-generator-for-woocommerce' ),
/* translators: %s: provider name, e.g. OpenAI */
'providerSaid' => __( '%s said:', 'ai-content-generator-for-woocommerce' ),
) );
if ( ! AI_Content_Generator_For_WooCommerce_Helper::has_active_connector() ) {
self::enqueue_provider_gate();
}
}
/**
* Grays out the generate buttons on the product edit screen while no AI
* provider is connected. Every button that starts a generation carries
* the wtofe-ai-action class; the script blocks its clicks and explains why
* in a popup that links to the setup wizard.
*/
private static function enqueue_provider_gate() {
wp_enqueue_style(
'wtofe-provider-gate',
WTOFE_AI_PLUGIN_URL . 'admin/css/provider-gate.css',
array(),
WTOFE_AI_VERSION
);
wp_enqueue_script(
'wtofe-provider-gate',
WTOFE_AI_PLUGIN_URL . 'admin/js/provider-gate.js',
array(),
WTOFE_AI_VERSION,
true
);
$can_connect = current_user_can( 'manage_woocommerce' );
wp_localize_script( 'wtofe-provider-gate', 'wtofeProviderGate', array(
'wizardUrl' => $can_connect ? WTOFE_Setup_Wizard::get_url() : '',
'i18n' => array(
'title' => __( 'No AI provider connected', 'ai-content-generator-for-woocommerce' ),
'message' => $can_connect
? __( 'Generating content needs an AI provider. Connecting one takes a couple of minutes.', 'ai-content-generator-for-woocommerce' )
: __( 'Generating content needs an AI provider. Ask a store manager to connect one.', 'ai-content-generator-for-woocommerce' ),
'linkText' => __( 'Run the setup wizard', 'ai-content-generator-for-woocommerce' ),
'reloadHint' => __( 'Connected a provider? Reload this page to start generating.', 'ai-content-generator-for-woocommerce' ),
),
) );
}
/** Adds loading-indicator markup to the product edit footer. */
public function add_description_generator_button() {
$screen = get_current_screen();
if ( ! $screen || 'post' !== $screen->base || 'product' !== $screen->post_type ) {
return;
}
require WTOFE_AI_PLUGIN_DIR . 'admin/partials/description-generator-footer.php';
}
// -------------------------------------------------------------------------
// AJAX: Images
// -------------------------------------------------------------------------
/**
* Ends the AJAX request unless the current user can edit this product.
*
* @param int $post_id
* @return void
*/
private function deny_unless_can_edit_product( $post_id ) {
if ( ! current_user_can( 'edit_product', $post_id ) ) {
wp_send_json_error( array( 'message' => __( 'You are not allowed to edit this product.', 'ai-content-generator-for-woocommerce' ) ) );
}
}
/** Handles AJAX request to generate product image URLs via OpenAI or Google Gemini. */
public function ajax_generate_product_image() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) );
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
if ( ! $post_id ) {
wp_send_json_error( array( 'message' => 'Invalid post ID.' ) );
}
$this->deny_unless_can_edit_product( $post_id );
$result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_images( $post_id );
if ( is_wp_error( $result ) ) {
wp_send_json_error( AI_Content_Generator_For_WooCommerce_Helper::get_error_response_data( $result ) );
}
wp_send_json_success( array_merge( array( 'message' => 'Images generated successfully.' ), $result ) );
}
/** Handles AJAX request to download and attach a generated image to a product. */
public function ajax_attach_generated_image() {
check_ajax_referer( 'wc_product_image_generator_nonce', 'nonce' );
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
$image_url = isset( $_POST['image_url'] ) ? esc_url_raw( $_POST['image_url'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
$is_gallery = isset( $_POST['is_gallery'] ) && '1' === $_POST['is_gallery'];
if ( ! $post_id || ! $image_url ) {
wp_send_json_error( array( 'message' => 'Missing required parameters.' ) );
return;
}
$this->deny_unless_can_edit_product( $post_id );
$attach_id = AI_Content_Generator_For_WooCommerce_Helper::attach_image_to_product( $post_id, $image_url, $is_gallery );
if ( is_wp_error( $attach_id ) ) {
wp_send_json_error( array( 'message' => $attach_id->get_error_message() ) );
}
if ( $is_gallery ) {
wp_send_json_success( array(
'message' => 'Image added to gallery successfully',
'attachment_id' => $attach_id,
'gallery_ids' => wc_get_product( $post_id )->get_gallery_image_ids(),
) );
}
wp_send_json_success( array(
'message' => 'Featured image set successfully',
'attachment_id' => $attach_id,
) );
}
/** Returns current gallery image IDs for a product. */
public function ajax_get_product_gallery() {
check_ajax_referer( 'wc_product_image_generator_nonce', 'nonce' );
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;
if ( ! $post_id ) {
wp_send_json_error( 'Invalid post ID' );
}
$this->deny_unless_can_edit_product( $post_id );
$gallery_ids = get_post_meta( $post_id, '_product_image_gallery', true );
wp_send_json_success( array_filter( explode( ',', $gallery_ids ) ) );
}
// -------------------------------------------------------------------------
// AJAX: Descriptions
// -------------------------------------------------------------------------
/** Handles AJAX request to generate full product description. */
public function ajax_generate_product_description() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) );
return;
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
if ( ! $post_id ) {
wp_send_json_error( array( 'message' => 'Invalid post ID.' ) );
return;
}
$this->deny_unless_can_edit_product( $post_id );
$tone = isset( $_POST['tone'] ) ? sanitize_text_field( wp_unslash( $_POST['tone'] ) ) : 'formal';
$result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_description( $post_id, $tone );
if ( is_wp_error( $result ) ) {
wp_send_json_error( AI_Content_Generator_For_WooCommerce_Helper::get_error_response_data( $result ) );
return;
}
wp_send_json_success( array_merge(
array( 'message' => 'Description generated successfully.' ),
$result,
array(
'badge_enabled' => AI_Content_Generator_For_WooCommerce_Helper::is_badge_enabled(),
'badge_message' => esc_html( AI_Content_Generator_For_WooCommerce_Helper::get_badge_message() ),
)
) );
}
/** Handles AJAX request to generate short product description. */
public function ajax_generate_product_short_description() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) );
return;
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
if ( ! $post_id ) {
wp_send_json_error( array( 'message' => 'Invalid post ID.' ) );
}
$this->deny_unless_can_edit_product( $post_id );
$tone = isset( $_POST['tone'] ) ? sanitize_text_field( wp_unslash( $_POST['tone'] ) ) : 'formal';
$result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_short_description( $post_id, $tone );
if ( is_wp_error( $result ) ) {
wp_send_json_error( AI_Content_Generator_For_WooCommerce_Helper::get_error_response_data( $result ) );
}
wp_send_json_success( array( 'description' => $result ) );
}
// -------------------------------------------------------------------------
// AJAX: Product Title (SEO Name)
// -------------------------------------------------------------------------
/** Handles AJAX request to generate SEO-friendly product name suggestions. */
public function ajax_generate_product_title() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) );
return;
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
$current_name = isset( $_POST['current_name'] ) ? sanitize_text_field( wp_unslash( $_POST['current_name'] ) ) : '';
if ( ! $post_id ) {
wp_send_json_error( array( 'message' => 'Invalid post ID.' ) );
return;
}
$this->deny_unless_can_edit_product( $post_id );
$result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_product_title( $post_id, $current_name );
if ( is_wp_error( $result ) ) {
wp_send_json_error( AI_Content_Generator_For_WooCommerce_Helper::get_error_response_data( $result ) );
return;
}
wp_send_json_success( array_merge( array( 'message' => 'Product name suggestions generated successfully.' ), $result ) );
}
// -------------------------------------------------------------------------
// AJAX: Brands
// -------------------------------------------------------------------------
/** Generates brand suggestions via GPT. */
public function ajax_generate_product_brands() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) );
return;
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
if ( ! $post_id ) { wp_send_json_error( array( 'message' => 'Invalid post ID.' ) ); return; }
$this->deny_unless_can_edit_product( $post_id );
$result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_brands( $post_id );
if ( is_wp_error( $result ) ) {
wp_send_json_error( AI_Content_Generator_For_WooCommerce_Helper::get_error_response_data( $result ) );
return;
}
wp_send_json_success( array_merge( array( 'message' => 'Brands generated successfully.' ), $result ) );
}
/** Creates a product_brand taxonomy term. */
public function ajax_create_product_brand_term() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) ); return;
}
$brand_name = isset( $_POST['brand_name'] ) ? sanitize_text_field( wp_unslash( $_POST['brand_name'] ) ) : '';
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
if ( ! $brand_name || ! $post_id ) { wp_send_json_error( array( 'message' => 'Missing required parameters.' ) ); return; }
$this->deny_unless_can_edit_product( $post_id );
$existing_term = get_term_by( 'name', $brand_name, 'product_brand' );
if ( $existing_term ) {
wp_send_json_success( array( 'term_id' => $existing_term->term_id, 'message' => 'Brand already exists.' ) ); return;
}
$result = wp_insert_term( $brand_name, 'product_brand' );
if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); return; }
wp_send_json_success( array( 'term_id' => $result['term_id'], 'message' => 'Brand created successfully.' ) );
}
/** Applies selected brand terms to a product. */
public function ajax_apply_product_brands() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) ); return;
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
$brands_to_apply = isset( $_POST['brands'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['brands'] ) ) : array();
if ( ! $post_id ) { wp_send_json_error( array( 'message' => 'Invalid post ID.' ) ); return; }
$this->deny_unless_can_edit_product( $post_id );
if ( empty( $brands_to_apply ) ) { wp_send_json_error( array( 'message' => 'No brands selected to apply.' ) ); return; }
if ( ! wc_get_product( $post_id ) ) { wp_send_json_error( array( 'message' => 'Invalid product.' ) ); return; }
AI_Content_Generator_For_WooCommerce_Helper::log_debug( 'Applying product brands', array( 'post_id' => $post_id, 'brands' => $brands_to_apply ) );
$brand_ids = array(); $brand_names = array();
foreach ( $brands_to_apply as $brand_name ) {
$existing_term = get_term_by( 'name', $brand_name, 'product_brand' );
if ( $existing_term ) {
$brand_ids[] = $existing_term->term_id;
$brand_names[ $existing_term->term_id ] = $existing_term->name;
} else {
$result = wp_insert_term( $brand_name, 'product_brand' );
if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => 'Failed to create brand: ' . $result->get_error_message() ) ); return; }
$brand_ids[] = $result['term_id'];
$brand_names[ $result['term_id'] ] = $brand_name;
}
}
$existing_brand_terms = wp_get_object_terms( $post_id, 'product_brand', array( 'fields' => 'ids' ) );
$all_brand_ids = array_unique( array_merge( $existing_brand_terms, $brand_ids ) );
$result = wp_set_object_terms( $post_id, $all_brand_ids, 'product_brand' );
if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => 'Failed to assign brands: ' . $result->get_error_message() ) ); return; }
AI_Content_Generator_For_WooCommerce_Helper::log_debug( 'Brands applied successfully', array( 'post_id' => $post_id, 'brand_ids' => $all_brand_ids ) );
wp_send_json_success( array( 'message' => 'Brands applied successfully.', 'brand_ids' => $all_brand_ids, 'brand_names' => $brand_names ) );
}
// -------------------------------------------------------------------------
// AJAX: Tags
// -------------------------------------------------------------------------
/** Generates tag/keyword suggestions via GPT. */
public function ajax_generate_product_tags() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) ); return;
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
if ( ! $post_id ) { wp_send_json_error( array( 'message' => 'Invalid post ID.' ) ); return; }
$this->deny_unless_can_edit_product( $post_id );
$result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_tags( $post_id );
if ( is_wp_error( $result ) ) {
wp_send_json_error( AI_Content_Generator_For_WooCommerce_Helper::get_error_response_data( $result ) );
return;
}
wp_send_json_success( array_merge( array( 'message' => 'Tags generated successfully.' ), $result ) );
}
/** Creates a product_tag taxonomy term. */
public function ajax_create_product_tag_term() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) ); return;
}
$tag_name = isset( $_POST['tag_name'] ) ? sanitize_text_field( wp_unslash( $_POST['tag_name'] ) ) : '';
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
if ( ! $tag_name || ! $post_id ) { wp_send_json_error( array( 'message' => 'Missing required parameters.' ) ); return; }
$this->deny_unless_can_edit_product( $post_id );
$existing_term = get_term_by( 'name', $tag_name, 'product_tag' );
if ( $existing_term ) {
wp_send_json_success( array( 'term_id' => $existing_term->term_id, 'message' => 'Tag already exists.' ) ); return;
}
$result = wp_insert_term( $tag_name, 'product_tag' );
if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); return; }
wp_send_json_success( array( 'term_id' => $result['term_id'], 'message' => 'Tag created successfully.' ) );
}
/** Applies selected tag terms to a product. */
public function ajax_apply_product_tags() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) ); return;
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
$tags_to_apply = isset( $_POST['tags'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['tags'] ) ) : array();
if ( ! $post_id ) { wp_send_json_error( array( 'message' => 'Invalid post ID.' ) ); return; }
$this->deny_unless_can_edit_product( $post_id );
if ( empty( $tags_to_apply ) ) { wp_send_json_error( array( 'message' => 'No tags selected to apply.' ) ); return; }
if ( ! wc_get_product( $post_id ) ) { wp_send_json_error( array( 'message' => 'Invalid product.' ) ); return; }
AI_Content_Generator_For_WooCommerce_Helper::log_debug( 'Applying product tags', array( 'post_id' => $post_id, 'tags' => $tags_to_apply ) );
$tag_ids = array(); $tag_names = array();
foreach ( $tags_to_apply as $tag_name ) {
$existing_term = get_term_by( 'name', $tag_name, 'product_tag' );
if ( $existing_term ) {
$tag_ids[] = $existing_term->term_id;
$tag_names[ $existing_term->term_id ] = $existing_term->name;
} else {
$result = wp_insert_term( $tag_name, 'product_tag' );
if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => 'Failed to create tag: ' . $result->get_error_message() ) ); return; }
$tag_ids[] = $result['term_id'];
$tag_names[ $result['term_id'] ] = $tag_name;
}
}
$existing_tag_terms = wp_get_object_terms( $post_id, 'product_tag', array( 'fields' => 'ids' ) );
$all_tag_ids = array_unique( array_merge( $existing_tag_terms, $tag_ids ) );
$result = wp_set_object_terms( $post_id, $all_tag_ids, 'product_tag' );
if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => 'Failed to assign tags: ' . $result->get_error_message() ) ); return; }
AI_Content_Generator_For_WooCommerce_Helper::log_debug( 'Tags applied successfully', array( 'post_id' => $post_id, 'tag_ids' => $all_tag_ids ) );
wp_send_json_success( array( 'message' => 'Tags applied successfully.', 'tag_ids' => $all_tag_ids, 'tag_names' => $tag_names ) );
}
// -------------------------------------------------------------------------
// AJAX: AI-Generated Flag
// -------------------------------------------------------------------------
/** Marks a product as having AI-generated content. */
public function ajax_mark_ai_generated() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) ); return;
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
if ( ! $post_id ) { wp_send_json_error( array( 'message' => 'Invalid post ID.' ) ); return; }
$this->deny_unless_can_edit_product( $post_id );
update_post_meta( $post_id, '_wtofe_ai_generated', '1' );
wp_send_json_success( array( 'message' => 'Product marked as AI-generated.' ) );
}
/** Removes the AI-generated flag from a product. */
public function ajax_unmark_ai_generated() {
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wc_product_image_generator_nonce' ) ) {
wp_send_json_error( array( 'message' => 'Invalid nonce.' ) ); return;
}
$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : false;
if ( ! $post_id ) { wp_send_json_error( array( 'message' => 'Invalid post ID.' ) ); return; }
$this->deny_unless_can_edit_product( $post_id );
delete_post_meta( $post_id, '_wtofe_ai_generated' );
wp_send_json_success( array( 'message' => 'AI-generated flag removed.' ) );
}
}