使用gpt生成wordpress产品标题

替换为自己的api,将下面的代码添加到主题的function.php文件中即可:

// 单个产品优化页面
function gpt_single_product_title_optimizer() {
    global $post;
    if ('product' !== $post->post_type) {
        return;
    }
    ?>
    <div class="options_group">
        <h3>Generate Optimized Title</h3>
        <textarea id="product_description" style="width:100%; height:100px;"><?php echo esc_textarea($post->post_content); ?></textarea><br>
        <button type="button" id="generate_title_button" class="button">Generate Title</button>
        <div id="generated_title"></div>
    </div>

    <script>
        jQuery(document).ready(function($) {
            $('#generate_title_button').click(function() {
                var description = $('#product_description').val();
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'generate_product_title',
                        description: description,
                    },
                    success: function(response) {
                        $('#generated_title').html('<strong>Optimized Title:</strong> ' + response.data);
                    }
                });
            });
        });
    </script>
    <?php
}
add_action('woocommerce_product_options_general_product_data', 'gpt_single_product_title_optimizer');

// 生成优化后的标题
function gpt_generate_product_title() {
    $description = sanitize_text_field($_POST['description']);
    
    // 调用GPT-3.5 API生成标题
    $generated_title = gpt_generate_title_from_description($description);
    
    wp_send_json_success($generated_title);
}
add_action('wp_ajax_generate_product_title', 'gpt_generate_product_title');

// GPT-3.5 API调用(使用cURL)
function gpt_generate_title_from_description($description) {
    $api_key = '替换为你的API密钥';  // 替换为你的API密钥
    $url = 'https://api.openai.com/v1/chat/completions';
    
    // 去除HTML标签
    $description = strip_tags($description);  // 清除所有HTML标签

    // 请求数据(chat模型需要格式化为messages数组)
    $data = array(
        'model' => 'gpt-3.5-turbo',
        'messages' => array(
            array(
                'role' => 'system', 
                'content' => 'You are an expert in generating optimized e-commerce product titles that are clear, concise, and easy to read. Ensure the title is formatted properly and adheres to SEO standards.'
            ),
            array(
                'role' => 'user', 
                'content' => "Create an e-commerce product title based on the following product description. The title should focus on the product's key features, functions, uses, target audience, and include relevant high-search volume keywords. The format should be as follows: [Product Type] with [Key Features/Functions], [Target Audience/Use], [Size/Material/Color], [Additional Features]. Ignore dimensions, weights, and any technical specifications that are irrelevant to the product's main selling points.\n\nProduct Description: [$description]"
            )
        ),
        'max_tokens' => 60,
    );

    // cURL 请求设置
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key,
    ));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    // 执行请求并获取响应
    $response = curl_exec($ch);

    // 检查 cURL 错误
    if(curl_errno($ch)) {
        $error_message = curl_error($ch);
        curl_close($ch);
        return "cURL Error: " . $error_message;  // 返回cURL错误信息
    }

    curl_close($ch);

    // 打印调试信息
    error_log('GPT API Response: ' . $response);  // 将响应写入服务器的错误日志

    // 解析API响应
    $response_data = json_decode($response, true);

    // 检查API返回的错误
    if (isset($response_data['error'])) {
        error_log('API Error: ' . $response_data['error']['message']);  // 记录API错误
        return 'API Error: ' . $response_data['error']['message'];
    }

    return $response_data['choices'][0]['message']['content'] ?? 'Error generating title';
}

// 批量生成标题操作
function gpt_bulk_title_generation($bulk_actions) {
    $bulk_actions['generate_titles'] = 'Generate Optimized Titles';
    return $bulk_actions;
}
add_filter('bulk_actions-edit-product', 'gpt_bulk_title_generation');

// 处理批量操作
function gpt_process_bulk_title_generation($redirect_to, $doaction, $post_ids) {
    if ('generate_titles' === $doaction) {
        foreach ($post_ids as $post_id) {
            $description = get_post_field('post_content', $post_id);
            $generated_title = gpt_generate_title_from_description($description);
            // 更新产品标题
            wp_update_post(array(
                'ID' => $post_id,
                'post_title' => $generated_title,
            ));
        }
        $redirect_to = add_query_arg('bulk_titles_generated', count($post_ids), $redirect_to);
    }
    return $redirect_to;
}
add_filter('handle_bulk_actions-edit-product', 'gpt_process_bulk_title_generation', 10, 3);

By 行政