Search code examples
wordpress

Add custom classes to "wp_get_attachment_image( $attachment_id)" wordpress function


I can get images using wp_get_attachment_image($attachment_id) wordpress function.It automatically add below code.

<img width="150" height="150" src="http://localhost/test2/wordpress/wp-content/uploads/2019/08/pexels-photo-1308624-150x150.jpeg" class="attachment-thumbnail size-thumbnail" alt="">

I want to add "alt" and another class using this function. To be specific I want to generate code like this.

<img width="150" height="150" src="http://localhost/test2/wordpress/wp-content/uploads/2019/08/pexels-photo-1308624-150x150.jpeg" class="attachment-thumbnail size-thumbnail custom-class" alt="Some Alt Value">

Solution

  • You can pass it like this.

    <?php echo wp_get_attachment_image( $attachment_id, 'thumbnail', "", ["class" => "my-custom-class","alt"=>"some"]); ?>
    

    You can read the full documentation here. https://developer.wordpress.org/reference/functions/wp_get_attachment_image/