Skip to content

Instantly share code, notes, and snippets.

@yratof
Last active February 15, 2018 13:51
Show Gist options
  • Save yratof/3d39580188dbdaaa6e254e7e56f0cbb8 to your computer and use it in GitHub Desktop.
Save yratof/3d39580188dbdaaa6e254e7e56f0cbb8 to your computer and use it in GitHub Desktop.
Call the featured image with an SVG fallback for featured image
<?php
class drivkraft_load {
/**
* Output featured image with SVG placeholder
* @return html
*/
static function featured_image( $post_id = null, $size = 'medium', $colour = '#f3f3f3' ) {
global $post;
// Fallback id if there isn't one
if ( ! $post_id ) {
$post_id = $post->id;
}
// Last check to fail
if ( ! $post_id ) {
return;
}
// Fetch the thumbnail ID
$thumbnail = get_post_thumbnail_id( $post_id );
// If no thumbnail, load SVG to keep alignment
if ( ! $thumbnail ) {
self::fallback_svg_image();
return;
}
// Get the meta for the thumbnail
$meta = wp_get_attachment_metadata( $thumbnail );
// Last check to fail
if ( empty( $meta ) ) {
self::fallback_svg_image();
return;
}
// Breakdown the attachment to get the ratio, fallback to 66.6666%
$ratio = ( $meta ? 100 / ( $meta['width'] / $meta['height'] ) : '66.666' );
$thumbnail = get_the_post_thumbnail( $post_id, $size );
?>
<div class="featured--thumbnail floating--image">
<a href="<?= the_permalink(); ?>">
<?= $thumbnail; ?>
<svg class="svg-placeholder" style="width: 100%; height: 0; padding-bottom: <?= $ratio; ?>%; background-color: <?= $colour; ?>;" viewBox="0 0 100 <?= $ratio; ?>"></svg>
</a>
</div>
<?php
}
static function fallback_svg_image() {
?>
<div class="featured--thumbnail no-thumbnail-image">
<a href="<?= the_permalink(); ?>">
<svg class="svg-placeholder" style="width: 100%; height: 0; padding-bottom: 66.666%; background-color: <?= $colour; ?>;" viewBox="0 0 100 66.666"></svg>
</a>
</div>
<?php
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment