2

What is the secure way to use wp_get_attachment_image() in a template?

2 Answers 2

2

Running the output through escaping function should be just fine. You can either use wp_kses_post(), which by default allows the same html attributes that you would use in the post content (see in code reference):

echo wp_kses_post( wp_get_attachment_image( $image_id ) ); 

or if you want to be more precise and strict, you can pass an array with allowed attributes for that particular context, like so:

echo wp_kses( wp_get_attachment_image( $image_id ), [
    'img' => [
        'src'      => true,
        'srcset'   => true,
        'sizes'    => true,
        'class'    => true,
        'id'       => true,
        'width'    => true,
        'height'   => true,
        'alt'      => true,
        'loading'  => true,
        'decoding' => true,
    ],
] );

It's up to you to decide what is allowed, just change the array contents to adjust to your needs!

1
  • 1
    Just in case it helps someone avoid some debugging time, wp_kses_post() removes the srcset and sizes attributes, so you will lose responsive images support by using it. See core.trac.wordpress.org/ticket/29807.
    – Marc
    Commented Sep 5, 2020 at 1:27
0

For now (28 of May 2021) wp_kses does not output srcset and sizes attributes (although ticket created ticket 7 years ago...).

But it's easy to enable via filter:

function starter_wpkses_post_tags( $tags, $context ) {
    $tags['img']['sizes']  = true;
    $tags['img']['srcset'] = true;
    return $tags;
}
add_filter( 'wp_kses_allowed_html', 'starter_wpkses_post_tags', 10, 2 );

Nowadays all modern browsers supports webp so it could be useful also to enable additional attributes for source tag, so full solution for srcset and sizes for both img and source tags is:

function starter_wpkses_post_tags( $tags, $context ) {
    $tags['img']['sizes']  = true;
    $tags['img']['srcset'] = true;
    $tags['source'] = array(
        'srcset' => true,
        'sizes'  => true,
        'type'   => true,
    );
    return $tags;
}
add_filter( 'wp_kses_allowed_html', 'starter_wpkses_post_tags', 10, 2 );

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.