Añadir Imagen Destacada a una entrada mediante programación
2.193 views
Si necesitamos añadir una imagen destacada (Featured Image) en una entrada WordPress, podemos usar la siguiente función. Necesitamos el post (o su ID) para poder asignarle la imagen.
Esta función nos genera los thumbnails que necesitan tanto WordPress como nuestro tema:
function add_imagen_destacada( $my_post ){ //la imagen DEBE estar en /uploads $filename = "mi_imagen_destacada.jpg"; $wp_upload_dir = wp_upload_dir(); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $filename, $my_post->ID ); $attach_data = wp_generate_attachment_metadata( $attach_id, $wp_upload_dir[ 'basedir' ] . "/" . $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $my_post->ID, $attach_id ); }