I’ve created a WordPress plugin that inserts width
and height
attributes to all images, for example:
<img src="https://placehold.it/100x50">
- to -
<img src="https://placehold.it/100x50" width="100" height="50">
Yet, when there are images that have blank dimensions (for both width
and height
), my code doesn’t doesn’t catch it, for example:
<img src="https://placehold.it/100x50" width="" height="">
However, when there is only one blank dimension, my plugin does catch it. The following two examples will work:
<img src="https://placehold.it/100x50" width="">
<img src="https://placehold.it/100x50" height="">
Here’s the source code. On line 43 (#), this is the logic I’m using to determine if an image is missing a width
/height
:
if ( ! in_array( 'width', $img[1] ) || ! in_array( 'height', $img[1] ) ) {
I’ve tried the following updated logic, but it doesn’t work:
if ( # Images with no width/height
! in_array( 'width', $img[1] ) || ! in_array( 'height', $img[1] ) ||
# Images with blank width/height
( in_array( 'width', $img[1] ) && in_array( '""', $img[1] ) ) || ( in_array( 'height', $img[1] ) && in_array( '""', $img[1] ) )
) {
Am I in the right area? What am I doing wrong in my logic?
1 Answer
Personally, the first thing I would do after matching the attributes is to create an associative array of:
array( 'attribute_name' => 'attribute_value' )
It will make it easier to get the attribute directly than having to search the array and I think overall it will make the code more direct. Since we know that index 0 is our attribute names and index 1 is our attribute values, we can use array_combine() to create the format listed above:
$attributes = array_combine( $img[1], $img[2] );
Finally, we can strip out any empty values from the array by finding the difference and then run the conditional.
$attributes = array_diff( $attributes, array( '""' ) );
Of course the above you would have to refactor your code to account for the new associative array $attributes['src']
and so forth. The problem with your original solution was you were searching for the value in the 1 index where you should have looked in the 2 index( which contains the values ):
if ( # Images with no width/height
! in_array( 'width', $img[1] ) || ! in_array( 'height', $img[1] ) ||
# Images with blank width/height
( in_array( 'width', $img[1] ) && in_array( '""', $img[2] ) ) || ( in_array( 'height', $img[1] ) && in_array( '""', $img[2] ) )
) {