Last active
March 19, 2020 18:25
-
-
Save tylerwiegand/f568796cba779fa1ce9f4e42ae6dc419 to your computer and use it in GitHub Desktop.
WP: Ultimate fallback solution to getting a thumbnail for a post
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 | |
function nb_get_post_thumbnail( $post_id = null, $size = 'medium', $attr = [] ) { | |
if(!$post_id) { | |
$post_id = get_the_ID(); | |
} | |
// Step 1: Use the featured image if it's there | |
if(!empty($image = get_the_post_thumbnail($post_id, $size, $attr))) { | |
return $image; | |
} | |
// Step 2: Try to get the first cover image | |
$content = get_post_field('post_content', $post_id); | |
// Get the the first cover, image, or media block you can find | |
preg_match('/<!-- (wp:cover|wp:image|wp:media-text) (.*)\/(?:\1) -->/ms', $content, $imageBlockMatches); | |
if(isset($imageBlockMatches[ 2 ])) { | |
preg_match('/(?:"id"|"mediaId")(?:\D*)(\d*)/', $imageBlockMatches[ 2 ], $imageId); | |
if(!empty($image = wp_get_attachment_image($imageId[ 1 ], $size, false, $attr))) { | |
return $image; | |
} | |
} | |
// The easy part is over. Now we need to delve into the rendered content! | |
$content = apply_filters('the_content', $content); | |
$content = str_replace(']]>', ']]>', $content); | |
// Get the first img tag's src attribute you see, then remove the -200x200 part, get the ID from the URL, Whabam | |
preg_match('/(?:<img)(?:.*?)(?:src=["|\'])(.*?)["|\']/ms', $content, $srcMatch); | |
if(isset($srcMatch[ 1 ]) && !empty($srcMatch[ 1 ])) { | |
$baseUrl = preg_replace('/(.*)(-\d*x\d*)/', '$1', $srcMatch[ 1 ]); | |
if(!empty($imageId = attachment_url_to_postid($baseUrl))) { | |
if(!empty($image = wp_get_attachment_image($imageId, $size, false, $attr))) { | |
return $image; | |
} | |
} | |
} | |
// If there is legitimately no image on your page, get the logo of the site as a final fallback. | |
if(empty($image)) { | |
if(!empty($image = wp_get_attachment_image(get_theme_mod('custom_logo'), $size, false, $attr))) { | |
return $image; | |
} | |
} | |
// And if there really is nothing...sorry =( | |
return ''; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment