How to use the below codes? – Watch the video below to Build SaaS AI Tools inside WordPress with ChatGPT API and how to use the codes below.
Here are the resources used:
function openai_generate_business_name() {
// Get the keywords from the AJAX request
if (!isset($_POST['keywords']) || empty($_POST['keywords'])) {
wp_send_json_error('Keywords are required');
return;
}
$keywords = sanitize_text_field($_POST['keywords']);
$prompt = "Generate a unique business name based on the following keywords: " . $keywords;
// OpenAI API URL and key
$api_url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'paste_your_api_key'; // 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_business_name', 'openai_generate_business_name');
add_action('wp_ajax_nopriv_openai_generate_business_name', 'openai_generate_business_name');
UI Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Business Name Generator</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Roboto', sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
box-sizing: border-box;
}
#business-name-generator {
max-width: 600px;
margin: 50px auto;
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
text-align: center;
}
#business-name-generator h1 {
margin-bottom: 20px;
}
#keywords, #generate-button, #result, #copy-button {
width: calc(100% - 20px);
padding: 10px;
margin: 10px 10px;
border-radius: 5px;
border: 1px solid #ddd;
font-size: 16px;
}
#generate-button, #copy-button {
color: #fff;
background-color: #007bff;
cursor: pointer;
border: none;
transition: background-color 0.3s;
}
#generate-button:hover, #copy-button:hover {
background-color: #0056b3;
}
.hidden {
display: none;
}
.loader {
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin: 10px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@media (max-width: 600px) {
#business-name-generator {
width: 90%;
margin: 20px auto;
}
}
</style>
</head>
<body>
<div id="business-name-generator">
<header>
<h1>Business Name Generator</h1>
</header>
<main>
<input type="text" id="keywords" placeholder="Enter keywords...">
<button id="generate-button">Generate Business Name!</button>
<div id="result-container" class="hidden">
<textarea rows='10' id="result" readonly></textarea>
<button id="copy-button">Copy</button>
</div>
</main>
<div id="loading" class="loader hidden"></div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const generateButton = document.getElementById('generate-button');
const copyButton = document.getElementById('copy-button');
const keywordsInput = document.getElementById('keywords');
const resultContainer = document.getElementById('result-container');
const resultTextarea = document.getElementById('result');
const loading = document.getElementById('loading');
generateButton.addEventListener('click', async (e) => {
e.preventDefault();
generateButton.disabled = true;
loading.classList.remove('hidden');
try {
const formData = new FormData();
formData.append('action', 'openai_generate_business_name');
formData.append('keywords', keywordsInput.value);
const response = await fetch('paste_your_website/wp-admin/admin-ajax.php', {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.success) {
resultTextarea.value = data.data.choices[0].message.content;
} else {
resultTextarea.value = 'An error occurred: ' + data.data;
}
} catch (error) {
resultTextarea.value = 'An error occurred: ' + error.message;
} finally {
loading.classList.add('hidden');
resultContainer.classList.remove('hidden');
generateButton.disabled = false;
}
});
copyButton.addEventListener('click', () => {
resultTextarea.select();
document.execCommand('copy');
alert('Copied to clipboard!');
});
});
</script>
</body>
</html>
