Skip to content

Commit 4478f53

Browse files
Skip images without src or srcset (#93)
1 parent ef932f0 commit 4478f53

3 files changed

Lines changed: 32 additions & 1 deletion

File tree

src/class-tiny-picture.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,10 @@ private function filter_images( $content ) {
195195
}
196196
$images = array();
197197
foreach ( $matches[0] as $img ) {
198+
// Skip images without src or srcset
199+
if ( ! preg_match( '/\b(?:src|srcset)\s*=/i', $img ) ) {
200+
continue;
201+
}
198202
$images[] = new Tiny_Source_Image(
199203
$img,
200204
$this->base_dir,

src/class-tiny-source-base.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,10 @@ protected function create_alternative_sources( $original_source_html ) {
189189
$srcsets = $this->get_image_srcsets( $original_source_html );
190190
if ( empty( $srcsets ) ) {
191191
// no srcset, try src attribute
192-
$srcsets[] = $this->get_image_src( $original_source_html );
192+
$src = $this->get_image_src( $original_source_html );
193+
if ( ! empty( $src ) ) {
194+
$srcsets[] = $src;
195+
}
193196
}
194197

195198
if ( empty( $srcsets ) ) {

test/unit/TinyPictureTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,4 +354,28 @@ public function test_does_not_register_hooks_when_pagebuilder_request()
354354

355355
$_GET = array();
356356
}
357+
358+
/**
359+
* images that have no src or srcset will be unchanged
360+
*/
361+
public function test_image_without_src() {
362+
$input = '<img alt="no source">';
363+
$expected = '<img alt="no source">';
364+
$output = $this->tiny_picture->replace_sources($input);
365+
366+
$this->assertSame($expected, $output);
367+
}
368+
369+
/**
370+
* Images with only a srcset are valid and will be wrapped
371+
*/
372+
public function test_image_with_only_srcset() {
373+
$this->wp->createImage(37857, '2025/09', 'test_250x250.webp');
374+
375+
$input = '<img srcset="/wp-content/uploads/2025/09/test_250x250.png 350w" alt="no source but has srcset">';
376+
$expected = '<picture><source srcset="/wp-content/uploads/2025/09/test_250x250.webp 350w" type="image/webp" /><img srcset="/wp-content/uploads/2025/09/test_250x250.png 350w" alt="no source but has srcset"></picture>';
377+
$output = $this->tiny_picture->replace_sources($input);
378+
379+
$this->assertSame($expected, $output);
380+
}
357381
}

0 commit comments

Comments
 (0)