Skip to content

Instantly share code, notes, and snippets.

@kamaravichow
Created March 27, 2024 09:13
Show Gist options
  • Save kamaravichow/90eb21da3be0608987771b5075491140 to your computer and use it in GitHub Desktop.
Save kamaravichow/90eb21da3be0608987771b5075491140 to your computer and use it in GitHub Desktop.
Template for WPCode snippet for an api call
<?php
function call_api() {
// Check if the request is coming from the correct origin
$prompt = $_POST['prompt'];
$api_url = "";
$headers = [
'Content-Type' => 'application/json',
];
$body = [
'query' => $prompt,
'lang' => 'en',
];
$args = [
'method' => 'POST',
'headers' => $headers,
'body' => json_encode($body),
'timeout' => 120
];
$response = wp_remote_request($api_url, $args);
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);
wp_send_json_success($data);
}
wp_die();
}
add_action('wp_ajax_call_api', 'call_api');
add_action('wp_ajax_nopriv_call_api', 'call_api');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment