i made wordpress plugin below.
issue: after form submitting, returns null
wordpress plugin:
// Register the shortcode
add_shortcode(‘chatgpt’, ‘chatgpt_shortcode’);
// Define the shortcode function
function chatgpt_shortcode($atts) {
// Extract shortcode attributes
$atts = shortcode_atts(array(
‘api_key’ => ‘Fills by my API key’,
), $atts);
$api_key = $atts[‘api_key’];
// Get user input and send request to ChatGPT
if (isset($_POST[‘user_input’])) {
$user_input = $_POST[‘user_input’];
$response = gpt_request($api_key, $user_input);
console_log($response);
return $response;
}
// Display user input form
ob_start();
?>
// Define the ChatGPT request function
function gpt_request($api_key, $user_input) {
$url = ‘https://api.openai.com/v1/engines/davinci-codex/completions’;
$prompt = 'Please help me with ’ . $user_input . ‘.’;
$headers = array(
‘Content-Type: application/json’,
'Authorization: Bearer ’ . $api_key,
);
$data = array(
‘prompt’ => $prompt,
‘max_tokens’ => 100,
‘temperature’ => 0.7,
);
$options = array(
‘http’ => array(
‘header’ => $headers,
‘method’ => ‘POST’,
‘content’ => json_encode($data),
),
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$response = json_decode($response, true);
return $response[‘choices’][0][‘text’];
}