Last active
November 28, 2017 02:27
-
-
Save urre/ce0d4de62c696493ae3a69ff93563d09 to your computer and use it in GitHub Desktop.
Display featured image with alt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
or