Escape post image attachments added to template

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

Topic escaping php images Wordpress

Category Web


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 );

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 codex):

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,
        'align'    => true,
    ],
] );

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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.