0

I found this great solution: Stop wordpress from hardcoding img width and height attributes

But I was wondering if I could do it only in one specific case and not in all the site because it messes up other stuff. This would be the case:

<?php echo wp_get_attachment_image($attachment->ID, 'six', false, $default_attr); ?>

Removing only height but not width in all the site would also work.

1
  • 1
    Can you explain why you want to do this? Understanding your need may open up other solutions.
    – Steve
    Commented Nov 1, 2012 at 23:17

3 Answers 3

2

This worked for me.

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

and then change

wp_get_attachment_image_src( $attachment_id, 'full' );

to

remove_width_and_height_attribute(wp_get_attachment_image_src( $attachment_id, 'full' ));
2
  • Instead of removing the width and height, you could also make them more useful by making a proper style attribute for them. Even though that's not what the OP asked, it will make the page less "jumpy" if there are lots of images to load: return preg_replace('/ width="(\d*)" height="(\d*)" /', ' style="width:$1px;height:$2px;" ', $html);
    – Sphinxxx
    Commented Jul 18, 2015 at 2:25
  • inline style is generally considered a bad idea. Both for maintenance sake and speed.
    – S..
    Commented Jul 18, 2015 at 7:14
1

You can also get the data for width and hight of a image.

$src = wp_get_attachment_image_src( $attachment_id, 'full' );
var_dump($src);

the var_dump output like this:

array
  0 => string 'http://example.com/wp-content/uploads/2009/08/DSC00261.JPG' (length=63)
  1 => int 1632
  2 => int 1224
  3 => boolean false

The results mean:

$src[0] => url
$src[1] => width
$src[2] => height
$src[3] => icon
0

One specific case and not in all the site.

Fx. If you want to remove width="400" from WordPress a HTML output function, you could do this:

Somewhere in a file:

ob_start(); // Start buf
wp_get_attachment_image($imageID, 'full', false); //'full' = size
$htmlString = ob_get_clean(); // output to variable
echo preg_replace('/width="\d*"/','',$variable); // Remove width attribute and whatever digit inside.

Maybe not the most elegant solution, but it gets the job done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.