Skip to content

Instantly share code, notes, and snippets.

@GaryJones
Forked from gregrickaby/echo-an-image.php
Last active April 16, 2019 14:55
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save GaryJones/9d38674c60a8e7319cc0 to your computer and use it in GitHub Desktop.
Save GaryJones/9d38674c60a8e7319cc0 to your computer and use it in GitHub Desktop.
<?php
/**
* Get post image.
*/
function wds_get_post_image( $size = 'thumbnail' ) {
// If featured image is present, use that
if ( has_post_thumbnail() ) {
return get_the_post_thumbnail( $size );
}
// Check for any attached image
$media = get_attached_media( 'image', get_the_ID() );
// Set up default image path
$media_url = get_stylesheet_directory_uri() . '/imgs/default-post-thumbnail.png';
// If an image is present, then use it as a thumbnail
if ( is_array( $media ) && 0 < count( $media ) ) {
$media = current( $media );
$media_url = ( 'thumbnail' === $size ) ? wp_get_attachment_thumb_url( $media->ID ) : wp_get_attachment_url( $media->ID );
}
return '<a href="' . esc_url( get_the_permalink() ) . '"><img src="' . esc_url( $media_url ) . '" alt="" /></a>';
}
@GaryJones
Copy link
Author

  • Refactor to avoid 2x else, using guard clauses to return early.
  • Fix missing escaping.
  • Fix errant ;.
  • Fix ternary condition.
  • Fix missing alt attributes required for valid markup.
  • Fix inconsistency where post thumbnail is immediately echoed if present, but fallback markup is returned.

Untested.

@gregrickaby
Copy link

Thanks. I've updated mine with (tested) code. https://gist.github.com/gregrickaby/dbc224eabbf3707d8c5d

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