Detener wordpress de los atributos de ancho y alto de img de codificación rígida

16

Me pregunto si hay una manera simple de detener WordPress de forma automática, codificando automáticamente los atributos de altura y anchura de la imagen, además de usar expresiones regulares ...

Como estoy usando una cuadrícula flexible para mi proyecto (¡quién no!), esto está causando algunos problemas de imagen funky.

    
pregunta Richard Sweeney 30.09.2011 - 09:18

6 respuestas

6

Puede obtener la URL de la imagen destacada y agregarla a su contenido manualmente, por ejemplo:

<?php 
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' ); 

if ($image) : ?>
    <img src="<?php echo $image[0]; ?>" alt="" />
<?php endif; ?> 
    
respondido por el Vilius Paulauskas 30.09.2011 - 10:12
14

Puede eliminar los atributos de ancho y alto filtrando la salida de la función image_downsize encontrada en wp-includes/media.php . Para hacer esto, escribe tu propia función y la ejecuta a través del archivo functions.php de tu tema o como un complemento.

Ejemplo :

Elimine los atributos width y height .

/**
 * This is a modification of image_downsize() function in wp-includes/media.php
 * we will remove all the width and height references, therefore the img tag 
 * will not add width and height attributes to the image sent to the editor.
 * 
 * @param bool false No height and width references.
 * @param int $id Attachment ID for image.
 * @param array|string $size Optional, default is 'medium'. Size of image, either array or string.
 * @return bool|array False on failure, array on success.
 */
function myprefix_image_downsize( $value = false, $id, $size ) {
    if ( !wp_attachment_is_image($id) )
        return false;

    $img_url = wp_get_attachment_url($id);
    $is_intermediate = false;
    $img_url_basename = wp_basename($img_url);

    // try for a new style intermediate size
    if ( $intermediate = image_get_intermediate_size($id, $size) ) {
        $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
        $is_intermediate = true;
    }
    elseif ( $size == 'thumbnail' ) {
        // Fall back to the old thumbnail
        if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
            $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
            $is_intermediate = true;
        }
    }

    // We have the actual image size, but might need to further constrain it if content_width is narrower
    if ( $img_url) {
        return array( $img_url, 0, 0, $is_intermediate );
    }
    return false;
}

Adjunte la nueva función al image_downsize hook:

/* Remove the height and width refernces from the image_downsize function.
 * We have added a new param, so the priority is 1, as always, and the new 
 * params are 3.
 */
add_filter( 'image_downsize', 'myprefix_image_downsize', 1, 3 );

Tampoco olvides escalar las imágenes correctamente en tu CSS:

/* Image sizes and alignments */
.entry-content img,
.comment-content img,
.widget img {
    max-width: 97.5%; /* Fluid images for posts, comments, and widgets */
}
img[class*="align"],
img[class*="wp-image-"] {
    height: auto; /* Make sure images with WordPress-added height and width attributes are scaled correctly */
}
img.size-full {
    max-width: 97.5%;
    width: auto; /* Prevent stretching of full-size images with height and width attributes in IE8 */
}

Espero que esto te ayude.

Saludos,

    
respondido por el byjml 30.09.2011 - 11:13
10

Puede usar el filtro post_thumbnail_html para eliminar el atributo:

function remove_img_attr ($html) {
    return preg_replace('/(width|height)="\d+"\s/', "", $html);
}

add_filter( 'post_thumbnail_html', 'remove_img_attr' );

Coloca esto en tu archivo functions.php

    
respondido por el Yi Jiang 26.09.2013 - 08:12
2

Puedes anular los estilos / atributos en línea con !important :

.wp-post-image {
    width: auto !important; /* or probably 100% in case of a grid */
    height: auto !important; 
}

No es la solución más limpia, pero resuelve tu problema.

    
respondido por el Rogier van der Linde 09.07.2016 - 14:55
2

La mejor solución es colocar jquery en pie de página

jQuery(document).ready(function ($) {
    jQuery('img').removeAttr('width').removeAttr('height');
});
    
respondido por el Asad Ali 23.10.2016 - 18:13
0

Solución CSS:

img[class*="align"], img[class*="wp-image-"] {
    width: auto;
    height: auto;
}

Esto permite que las imágenes de respuesta funcionen como deberían, mientras que usted mantiene los atributos de ancho y alto en el elemento img, lo que probablemente sea mejor para navegadores más antiguos, rendimiento y / o para pasar validadores de HTML.

Solución PHP:

Esto evitará la adición de atributos de ancho / alto en cualquier medio recién agregado en el editor de WP (a través de 'Agregar medio'). Para tu información, ¡también puede afectar tus títulos de imagen!

function remove_widthHeight_attribute( $html ) {
   $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
   return $html;
}

add_filter( 'post_thumbnail_html', 'remove_widthHeight_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_widthHeight_attribute', 10 );
    
respondido por el MarsAndBack 07.08.2018 - 18:54

Lea otras preguntas en las etiquetas