Skip to content

Instantly share code, notes, and snippets.

@natzar
Last active October 24, 2023 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natzar/48fdc33b0bda8fafd8053d8b7420bd52 to your computer and use it in GitHub Desktop.
Save natzar/48fdc33b0bda8fafd8053d8b7420bd52 to your computer and use it in GitHub Desktop.
[ai_image prompt="Descripción de la imagen que quieres"]
Shortcode:
[ai_image prompt="Descripción de la imagen que quieres"]
Añadir en functions.php:
function generate_image_from_prompt($atts) {
$atts = shortcode_atts(array('prompt' => ''), $atts);
$prompt = $atts['prompt'];
// Lógica para obtener la imagen de la API en función del prompt
$image_url = get_image_from_api($prompt);
return "<img src='{$image_url}' alt='{$prompt}'>";
}
add_shortcode('ai_image', 'generate_image_from_prompt');
function get_image_from_api($prompt) {
$cache_directory = plugin_dir_path(__FILE__) . 'ai_images_cache/';
$hashed_prompt = md5($prompt);
$cached_image_path = $cache_directory . $hashed_prompt . '.jpg';
// Si la imagen ya está en caché, la servimos directamente
if (file_exists($cached_image_path)) {
return plugin_dir_url(__FILE__) . 'ai_images_cache/' . $hashed_prompt . '.jpg';
}
// Si no, solicitamos a la API.
// MODIFICAR AQUÍ: Aquí es donde hay que ajustar para la API que se vaya a usar.
$api_url = "URL_DE_LA_API?prompt=" . urlencode($prompt);
$response = wp_remote_get($api_url);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// Descargar la imagen: IMPORTANTE ajustar el "image_url" nombre de campo para ajustarlo a la API que se vaya a usar
$image_content = wp_remote_retrieve_body(wp_remote_get($data['image_url']));
file_put_contents($cached_image_path, $image_content);
return plugin_dir_url(__FILE__) . 'ai_images_cache/' . $hashed_prompt . '.jpg';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment