Generate WordPress AI Endpoints
by hassancs91 •
0
Generate Custom WordPress Endpoints Powered by OpenAI API to create any idea you want!
Code Assistance
#lwh
Version
imports
Try This Prompt
Prompt Template
Your Task is to create a WordPress custom endpoint based on the following:
Requirements:
Technical Specifications:
Use WordPress REST API registration
Call OpenAI API (gpt-4o-mini model)
Use JSON schema for structured API responses
Include proper error handling
Code Structure Template:
REST API Registration - Register endpoint with proper parameters
Main API Function - Handle OpenAI API calls with custom prompt
Endpoint Callback - Process request parameters and return response
Required Features:
Ask clarifying questions first - Before generating code, ask the user what parameters would be useful for customization
Flexible parameter count - Some tools may need many parameters, some may need just one, some may need none. Only include parameters that actually add value.
Proper input sanitization
Structured JSON response format
Error handling for API failures
CORS support for frontend integration
API Configuration:
Timeout: 120 seconds
CORS: Allow all origins (Access-Control-Allow-Origin: *)
Model: gpt-4o-mini
Temperature: 0.7 (adjust if needed for the specific use case)
Max Tokens: Appropriate for the content type
Example Code to use as a reference:
// Register the REST API endpoint
add_action('rest_api_init', function() {
register_rest_route('blog/v1', '/generate-story', [
'methods' => 'POST',
'callback' => 'custom_app_generate_openai_json',
'permission_callback' => '__return_true',
'args' => [
'topic' => [
'required' => true,
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field'
],
'genre' => [
'required' => false,
'type' => 'string',
'default' => 'general',
'sanitize_callback' => 'sanitize_text_field'
],
'length' => [
'required' => false,
'type' => 'string',
'default' => 'medium',
'sanitize_callback' => 'sanitize_text_field'
],
'tone' => [
'required' => false,
'type' => 'string',
'default' => 'professional',
'sanitize_callback' => 'sanitize_text_field'
]
]
]);
// Add CORS headers
add_action('rest_api_init', function() {
remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
add_filter('rest_pre_serve_request', function($value) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
return $value;
});
}, 15);
});
function custom_app_call_openai_api($topic, $genre = 'general', $length = 'medium', $tone = 'professional', $return_json = false) {
// Determine word count based on length
$length_map = [
'short' => '300-500',
'medium' => '500-800',
'long' => '800-1200'
];
$word_count = $length_map[$length] ?? '500-800';
$prompt = "Write a compelling {$word_count} word story about: $topic.
Genre: $genre
Tone: $tone
Include engaging characters, dialogue, and a clear beginning, middle, and end. Make it well-structured and {$tone} in style.
Respond with JSON including the title, story content, word count, genre, length, and tone.";
$api_key = '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';
$url = 'https://api.openai.com/v1/chat/completions';
// Adjust max tokens based on length
$token_map = [
'short' => 800,
'medium' => 1200,
'long' => 1800
];
$max_tokens = $return_json ? ($token_map[$length] ?? 1200) : 20;
$body_data = [
'model' => 'gpt-4o-mini',
'messages' => [[ 'role' => 'user', 'content' => $prompt ]],
'max_tokens' => $max_tokens,
'temperature' => 0.7
];
if ($return_json) {
$body_data['response_format'] = [
'type' => 'json_schema',
'json_schema' => [
'name' => 'story_response',
'strict' => true,
'schema' => [
'type' => 'object',
'properties' => [
'title' => [
'type' => 'string',
'description' => 'An engaging title for the story'
],
'story' => [
'type' => 'string',
'description' => 'The complete story content'
],
'word_count' => [
'type' => 'integer',
'description' => 'Approximate word count of the story'
],
'genre' => [
'type' => 'string',
'description' => 'The genre of the story'
],
'length' => [
'type' => 'string',
'description' => 'The length category of the story'
],
'tone' => [
'type' => 'string',
'description' => 'The tone used in the story'
]
],
'required' => ['title', 'story', 'word_count', 'genre', 'length', 'tone'],
'additionalProperties' => false
]
]
];
}
$response = wp_remote_post($url, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
],
'body' => json_encode($body_data),
'timeout' => 120
]);
if (is_wp_error($response)) return $response;
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($return_json) {
return json_decode($body['choices'][0]['message']['content'], true);
} else {
return trim($body['choices'][0]['message']['content']);
}
}
function custom_app_generate_openai_json($request) {
$topic = $request->get_param('topic');
$genre = $request->get_param('genre') ?: 'general';
$length = $request->get_param('length') ?: 'medium';
$tone = $request->get_param('tone') ?: 'professional';
$result = custom_app_call_openai_api($topic, $genre, $length, $tone, true);
if (is_wp_error($result)) return $result;
return $result;
}
?>
Usage Example Pattern:
USER PROVIDES: Idea: "Create an AI email marketing campaign generator"
CLAUDE ASKS: "What parameters would be useful? Would you like options for:
- Email type (promotional, newsletter, welcome, etc.)?
- Tone (professional, casual, urgent)?
- Length (short, medium, long)?
- Target audience?
- Call-to-action style?"
USER RESPONDS: "Yes to email type, tone, and CTA style"
CLAUDE GENERATES: Complete WordPress endpoint code with those specific parameters
You should provide:
Complete PHP Code - Full WordPress endpoint implementation
API Testing Details - URL, request body examples, cURL commands
Response Examples - Expected JSON response format
Testing Instructions - How to test the endpoint
My Idea: {{idea}}