Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created August 3, 2018 11:32
Show Gist options
  • Select an option

  • Save morgyface/6e837458b78e7f2b9b82670dd8b0c15d to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/6e837458b78e7f2b9b82670dd8b0c15d to your computer and use it in GitHub Desktop.
WordPress | Function | Featured image or SVG
<?php
// If the post does not have a featured image
function feat_img_fallback($image_size, $post_id, $alt) {
if ( has_post_thumbnail($post_id) ) {
$image_id = get_post_thumbnail_id($post_id);
$image_src = wp_get_attachment_image_src($image_id, $image_size);
$image_url = $image_src[0];
$image = '<img src="' . $image_url . '" alt="' . $alt . '">';
} else {
$image_width = $image_size . '_size_w';
$image_width = get_option($image_width);
$image_height = $image_size . '_size_h';
$image_height = get_option($image_height);
$image = '<svg xmlns="http://www.w3.org/2000/svg" width="' . $image_width . '" height="' . $image_height . '"><path d="M0 0h' . $image_width . 'v' . $image_height . 'H0z"/></svg>';
}
return $image;
}
?>
@morgyface
Copy link
Author

morgyface commented Aug 3, 2018

Featured image or inline SVG

In short you pass in the size you need (standard WP sizes), the post ID and the desired alt tag.

The function then checks for a featured image, if it's available it returns the relevant image.

If there's no attached image, the function grabs the sizing of the desired image size and creates and returns an inline SVG.

There's a variation on this here which returns the URL of the featured image or a placeholder URL.

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