How to use the prompts below? – Watch the video below to learn how to use the resources below to get the best results in your work.
These are the code snippets used in our Mini-Course: WordPress Custom API Endpoints: Build, Innovate, and Secure!
- Custom API Prefix: Learn how to change the default
wp-json
prefix tocustom-api
To personalize your site’s API URL structure. - Dummy Endpoint: We start with a simple endpoint that returns a static message, serving as a gentle introduction to WordPress API development.
- Parameter Handling: Explore how to enhance your API’s functionality by accepting parameters and delivering tailored responses.
- Integration with OpenAI: The course features an advanced example where you will create a functional API endpoint that interacts with OpenAI’s API to generate blog titles based on user input. This endpoint handles user authentication, constructs HTTP requests, and processes AI-generated content.
If you don’t have Python installed here is step by step guide. So Python and Visual studio code is required for this project.
add_filter('rest_url_prefix', 'custom_rest_url_prefix'); function custom_rest_url_prefix() { return 'custom-api'; // Change this to your desired prefix } function return_dummy_text() { return 'This is a custom WordPress API Endpoint'; } function generate_dummy_response( WP_REST_Request $request ) { $parm1 = $request->get_param('parm1'); // Dummy static response $dummy_response = array( 'success' => true, 'message' => 'done', 'result' => "Parameter one value: " . $parm1 ); // Return the dummy response as an associative array return $dummy_response; } function generate_blog_titles_openai( WP_REST_Request $request ) { $user_topic = $request->get_param('topic'); // OpenAI API URL and key $api_url = 'https://api.openai.com/v1/chat/completions'; $api_key = 'sk-XXX'; // Headers for the OpenAI API $headers = [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key ]; $conversation_history[] = [ 'role' => 'user', 'content' => 'generate 5 blog post titles about the following topic: ' . $user_topic ]; // Body for the OpenAI API $body = [ 'model' => 'gpt-3.5-turbo', // You can change the model if needed 'messages' => $conversation_history, 'temperature' => 0.7 // You can adjust this value based on desired creativity ]; // 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); $response_body = wp_remote_retrieve_body($response); $data = json_decode($response_body, true); // Handle the response $content = $data['choices'][0]['message']['content']; return [ 'success' => true, 'message' => 'Response Generated', 'result' => $content ]; } // Register a Custom REST API endpoint add_action('rest_api_init', function () { register_rest_route('v1', '/generate-titles/', array( 'methods' => 'GET', 'callback' => 'generate_blog_titles_openai', 'permission_callback' => function () { return is_user_logged_in(); } //'permission_callback' => '__return_true', // This makes the endpoint publicly accessible. Adjust the permissions as necessary. )); });
The Code Explanation is Below:
Part 1: Changing the API URL Prefix
add_filter('rest_url_prefix', 'custom_rest_url_prefix');
function custom_rest_url_prefix() {
return 'custom-api'; // Change this to your desired prefix
}
- Imagine your WordPress website has a special secret passage called “API.”
- But you don’t like its name and want to call it something cooler, like “custom-api.”
- This piece of code tells WordPress, “Hey! From now on, call the secret passage ‘custom-api’ instead of the boring default name.”
Part 2: Returning Dummy Text
function return_dummy_text() {
return 'This is a custom WordPress API Endpoint';
}
- This function is like a magic box. When someone says “Show me something!” it will always say, “This is a custom WordPress API Endpoint.”
- It’s like when you ask someone for their favorite phrase, and they always say the same thing!
Part 3: Generating a Dummy Response
function generate_dummy_response( WP_REST_Request $request ) {
$parm1 = $request->get_param('parm1');
$dummy_response = array(
'success' => true,
'message' => 'done',
'result' => "Parameter one value: " . $parm1
);
return $dummy_response;
}
- Think of this as a game where someone gives you a secret word (called a “parameter”), and you say back, “Here is your word!”
- In this case, if someone gives you parm1 (a secret word), you return something like “Parameter one value: [the secret word they gave].”
- You also add some extra stuff like saying, “Success! Done!”
Part 4: Talking to OpenAI and Generating Blog Titles
function generate_blog_titles_openai( WP_REST_Request $request ) {
$user_topic = $request->get_param('topic');
$api_url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'sk-XXX';
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
];
$conversation_history[] = [
'role' => 'user',
'content' => 'generate 5 blog post titles about the following topic: ' . $user_topic
];
$body = [
'model' => 'gpt-3.5-turbo',
'messages' => $conversation_history,
'temperature' => 0.7
];
$args = [
'method' => 'POST',
'headers' => $headers,
'body' => json_encode($body),
'timeout' => 120
];
$response = wp_remote_request($api_url, $args);
$response_body = wp_remote_retrieve_body($response);
$data = json_decode($response_body, true);
$content = $data['choices'][0]['message']['content'];
return [
'success' => true,
'message' => 'Response Generated',
'result' => $content
];
}
- Now we want to ask a super-smart robot (OpenAI) to come up with blog title ideas.
- First, we ask the user for a “topic” (like “Dinosaurs”).
- We send this topic to the robot (OpenAI) and say, “Hey robot, can you give me 5 blog titles about Dinosaurs?”
- The robot then sends back some cool titles, and we share those with the user.
- This is done by building a “letter” (an API request) and sending it to the robot using a secret password (API key).
Part 5: Creating the Custom API Endpoint
add_action('rest_api_init', function () {
register_rest_route('v1', '/generate-titles/', array(
'methods' => 'GET',
'callback' => 'generate_blog_titles_openai',
'permission_callback' => function () {
return is_user_logged_in();
}
));
});
- This part sets up a special door in your website where people can ask the robot for blog titles.
- You decide that only people who are logged in (like when you’re logged into a computer game) can use this door.
- If they are logged in, they can ask for the titles, and the door will let them in.