sg

Home » Snippets » sg
0

Created with:

Visibility: 

public

Creator: Nicolas

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<function openai_generate_text() {
    // Get the topic and language from the AJAX request
    $prompt = $_POST['prompt'];
    $language = $_POST['language'];

    // Adjust the prompt based on the selected language
    if ($language === 'el') {
        $prompt = "Συζήτηση στα Ελληνικά για " . $prompt;
    } else {
        $prompt = "Conversation in English about " . $prompt;
    }

    // OpenAI API URL and key
    $api_url = 'https://api.openai.com/v1/chat/completions';
    $api_key = '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';  // Replace with your actual OpenAI API key

    // Headers for the OpenAI API
    $headers = [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer ' . $api_key
    ];

    // Body for the OpenAI API
    $body = [
        'model' => 'gpt-3.5-turbo',
        'messages' => [['role' => 'user', 'content' => $prompt]],
        'temperature' => 0.7
    ];

    // Args for the WordPress HTTP API
    $args = [
        'method' => 'POST',
        'headers' => $headers,
        'body' => json_encode($body),
        'timeout' => 120
    ];

    // Send the request
    $response = wp_remote_request($api_url, $args);

    // Handle the response
    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        wp_send_json_error("Something went wrong: $error_message");
    } else {
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            wp_send_json_error('Invalid JSON in API response');
        } elseif (!isset($data['choices'])) {
            wp_send_json_error('API request failed. Response: ' . $body);
        } else {
            wp_send_json_success($data);
        }
    }

    // Always die in functions echoing AJAX content
    wp_die();
}

add_action('wp_ajax_openai_generate_text', 'openai_generate_text');
add_action('wp_ajax_nopriv_openai_generate_text', 'openai_generate_text');


function enqueue_custom_scripts() {
    // Enqueue jsPDF library
    wp_enqueue_script('jspdf', 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js', array(), null, true);

    // Enqueue docx library
    wp_enqueue_script('docx', 'https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.27.0/docxtemplater-latest.min.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');?php
				

Register an account to save your snippets or go Pro to get more features.