function generate_openai_audio_on_publish($post_id) {
if (get_post_type($post_id) !== 'post') return;
$post = get_post($post_id);
$text = wp_strip_all_tags($post->post_content);
$text = mb_substr($text, 0, 4000); // Limit text length
$api_key = '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'; // Replace with your real key
$voice = 'nova'; // voice option
$response = wp_remote_post('https://api.openai.com/v1/audio/speech', [
'headers' => [
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json'
],
'body' => json_encode([
'model' => 'tts-1',
'voice' => $voice,
'input' => $text
])
]);
if (is_wp_error($response)) return;
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (!$data || empty($data['audio_url'])) return;
$audio_url = $data['audio_url'];
// Download audio file from OpenAI
$audio_response = wp_remote_get($audio_url);
if (is_wp_error($audio_response)) return;
$audio_content = wp_remote_retrieve_body($audio_response);
if (!$audio_content) return;
// Save the audio file to uploads folder
$upload = wp_upload_bits("post-{$post_id}.mp3", null, $audio_content);
if ($upload['error']) return;
// Save URL in post meta for later retrieval
update_post_meta($post_id, '_openai_audio_url', $upload['url']);
}
Rodrigo Duterte - newslineph.press