0

please help me, my website notice error Message.

On error.log notice Undefined Array Key "srcset"

This is my code on WordPress, and i'am use PHP Version 8.0.

function my_plugin_filter_attachment_webp( $attr ) {
global $webp;
if ( ! is_singular( array( 'post', 'page' ) ) && ! ( is_home() || is_tag() || is_category() || is_tax() ) || ( true !== $webp ) || ( is_admin() ) ) {return $attr; } else {
$attr['src'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['src'] );
$attr['src'] = str_replace( array( '.jpg' ), '.jpg.webp', $attr['src'] );
$attr['src'] = str_replace( array( '.png' ), '.png.webp', $attr['src'] );
$attr['srcset'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] );
$attr['srcset'] = str_replace( array( '.jpg' ), '.jpg.webp', $attr['srcset'] );
$attr['srcset'] = str_replace( array( '.png' ), '.png.webp', $attr['srcset'] );
return $attr;
}
}
add_filter( 'wp_get_attachment_image_attributes', 'my_plugin_filter_attachment_webp', 10, 1 );

How to fix, my dear friend?

1 Answer 1

1

Latest versions of PHP get mad if you try to reference array parameters that don't exist. It's a 'warning' type error, so the page will still load.

You need to test for existence of an array parameter before you reference it. So instead of

$attr['srcset'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] );

Put those array references in an IF statement

if (isset($attr['srcset']) {
   $attr['srcset'] = str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] );
}

That will eliminate that warning message. You will have to do similar to all array elements that may not exist.

You also do something like this:

$attr['srcset'] = ($attr['srcset']) ? str_replace( array( '.jpeg' ), '.jpeg.webp', $attr['srcset'] ) : "";

Which will set that array element to blank if it doesn't exist, so you won't have to test for it the next time you use it.

Your Answer

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

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