Created
August 3, 2018 11:32
-
-
Save morgyface/6e837458b78e7f2b9b82670dd8b0c15d to your computer and use it in GitHub Desktop.
WordPress | Function | Featured image or SVG
This file contains hidden or 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 | |
| // 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; | |
| } | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.