Advertisement
clongarela

WP rename uploaded images

Dec 21st, 2017
333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. /**
  3.  * Cambia el nombre del archivo a una versión segura y sanitizada.
  4.  *
  5.  * @param string $filename     Nombre del archivo una vez pasados los primeros filtros de WP.
  6.  * @param string $filename_raw Nombre del archivo "en crudo" al subirse.
  7.  *
  8.  * @return string
  9.  *
  10.  * @since 1.2.0
  11.  */
  12. function cl_nombre_archivo( $filename, $filename_raw ) {
  13.     $info           = pathinfo( $filename_raw );
  14.     $nombre_archivo = $info['filename'];
  15.  
  16.     if ( ! empty( $info['extension'] ) ) {
  17.         $ext = $info['extension'];
  18.     } else {
  19.         $ext = '';
  20.     }
  21.  
  22.     $nombre_archivo = remove_accents( $nombre_archivo );
  23.     $nombre_archivo = str_replace( '_', '-', $nombre_archivo );
  24.     $nombre_archivo = str_replace( '%20', '-', $nombre_archivo );
  25.     $nombre_archivo = sanitize_title( $nombre_archivo );
  26.     $nombre_archivo = $nombre_archivo . '.' . $ext;
  27.  
  28.     return $nombre_archivo;
  29. }
  30. add_filter( 'sanitize_file_name', 'cl_nombre_archivo', 10, 2 );
  31.  
  32. /**
  33.  * Añade al ALT de las imágenes el título de la foto.
  34.  *
  35.  * @param int    $meta_id    Id del metadato.
  36.  * @param int    $post_id    Id del post.
  37.  * @param string $meta_key   Clave del metadato.
  38.  * @param mixed  $meta_value Valor del metadato.
  39.  *
  40.  * @return void
  41.  *
  42.  * @since 1.2.0
  43.  */
  44. function cl_alt_after_post_meta( $meta_id, $post_id, $meta_key, $meta_value ) {
  45.     if ( '_wp_attachment_metadata' === $meta_key ) {
  46.         $titulo = get_the_title( $post_id ); // Obtenemos el título del archivo.
  47.  
  48.         // Actualizamos el Texto del ALT.
  49.         update_post_meta( $post_id, '_wp_attachment_image_alt', $titulo );
  50.     }
  51. }
  52. add_action( 'added_post_meta', 'cl_alt_after_post_meta', 10, 4 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement