<?php
/*
Plugin Name: Codeur Blog GPT
Plugin URI: http://localhost/wordpress/wp-admin/codeur-blog-gpt/
Description: Codeur Blog is a plugin that allows you to generate article to your WordPress site.
Version: 0.1.0
Requires at least: 6.0
Requires PHP: 7.4
Author: Codeur.com
Author URI: https://codeur.com/
License: GPLv2 or later
Text Domain: codeur-blog-gpt
*/

// Make sure we don't expose any info if called directly
if ( !function_exists( 'add_action' ) ) {
  echo 'Hi there!  I\'m just a plugin, not much I can do when called directly.';
  exit;
}

add_shortcode('codeur-blog-gpt', 'codeur_blog_gpt_shortcode');

function codeur_blog_gpt_shortcode(){
    ob_start();

?>

    <div id="codeur-blog-gpt">
        <h2>Top 10 villes à visiter en France</h2>
        <?php
            $prompt = "Ecris-moi un article qui parle des 10 meilleurs villes de la France";
            $output = codeur_blog_ask_gpt( $prompt );
            echo wpautop( esc_html($output) );
        ?>
    </div>

<?php

    $content = ob_get_contents();
    ob_end_clean();
    return $content;

}

/**
 * @param string 
 * @return string   
 */
function codeur_blog_ask_gpt( $prompt ){
 
    // Construire les arguments d'en-tête.
    $url ="https://api.openai.com/v1/completions";
    $apikey = CODEUR_BLOG_OPENAI_API_KEY;

    $headers = array(
        'Authorization' => 'Bearer ' .$apikey,
        'Content-Type'  => 'application/json',
    );
    
    // Construire le corps de la requête.
    $body = array(
        'model'  => 'text-davinci-003',
        'prompt' => $prompt,
        'max_tokens' => 100,
        'temperature' => 0.3,
    );

    //  Faire la demande.
    $args = array(
        'headers' => $headers,
        'body'  => json_encode($body),
        'method'    => 'POST',
    );

    $response = wp_remote_post($url, $args);

    //  Vérifier les erreurs.
    if (is_wp_error( $response ) ){
        $error = $response->get_error_message();
        return "ERROR:" .$error;
    }

    //  Décoder la réponse.
    $response_body = json_decode( $response['body'] );
    $choice_text = $response_body->choices[0]->text;
    return $choice_text;
 
}
?>

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.