Skip to content

Instantly share code, notes, and snippets.

@urre
Last active November 28, 2017 02:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save urre/ce0d4de62c696493ae3a69ff93563d09 to your computer and use it in GitHub Desktop.
Save urre/ce0d4de62c696493ae3a69ff93563d09 to your computer and use it in GitHub Desktop.
Display featured image with alt
<?php
/**
* Show post thumbnail width alt
*
* @author Urban Sanden <urban@sprintworks.se>
* @param type|string $size Size like 'full', 'large', 'medium', 'thumbnail'.
* @param type|object $post Post object.
* @param type|string $fallbacksize_x Fallback image size x.
* @param type|string $fallbacksize_y Fallback image size y.
* @param type|string $fallbacktext Fallbacktext.
*/
function showPostThumbnail( $size, $post, $fallbacksize_x = '200', $fallbacksize_y = '200', $fallbacktext = 'Bild saknas' ) {
// Get featured image id.
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), $size );
// Get image alt text.
$image_alt = empty( get_post_meta( get_post_thumbnail_id( $post->ID ), '_wp_attachment_image_alt', true ) ) ? get_the_title( $post->ID ) : get_post_meta( get_post_thumbnail_id( $post->ID ), '_wp_attachment_image_alt', true );
// Display image, or fallback image.
if ( $featured_image[0] ) : ?>
<img src="<?php echo esc_url( $featured_image[0] ) ?>" alt="<?php echo esc_attr( $image_alt ) ?>">
<?php else : ?>
<img src="<?php echo esc_url( sprintf ( 'http://dummyimage.com/%sx%s/cccccc/ffffff/ccc.jpg&text=%s', $fallbacksize_x, $fallbacksize_y, urlencode($fallbacktext) ) ); ?>">
<?php endif;
}
@urre
Copy link
Author

urre commented Sep 20, 2016

Usage:

<?php showPostThumbnail('large', $post, '170', '120'); ?>

or

<?php showPostThumbnail('large', $post, '170', '120', 'Missing image'); ?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment