0

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

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!

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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