Created
March 27, 2024 09:13
-
-
Save kamaravichow/90eb21da3be0608987771b5075491140 to your computer and use it in GitHub Desktop.
Template for WPCode snippet for an api call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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