Created
February 1, 2014 23:08
-
-
Save simongcc/8760421 to your computer and use it in GitHub Desktop.
Wordpress image fall back algorithm
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
/* | |
fallback order: | |
use post thumbnail(featured post) if available, otherwise | |
use first attachment image if available, otherwise | |
use first image link if available, otherwise | |
stay blank... | |
*/ | |
// inside a loop | |
$ID = get_the_ID(); | |
//default is thumbnail | |
if($include_post_thumbnail == "false"): | |
$POST_THUMBNAIL = ''; | |
else: | |
$POST_THUMBNAIL = get_the_post_thumbnail($ID, array($post_thumbnail_width, $post_thumbnail_height)); | |
// var_dump( $POST_THUMBNAIL ); | |
// if post thumbnail is empty, fall back to first attachment in thumb-featured size | |
if( empty( $POST_THUMBNAIL ) ): | |
$args = array( | |
'post_type' => 'attachment', | |
'numberposts' => -1, | |
'post_status' => null, | |
'post_parent' => $ID | |
); | |
$attachments = get_posts($args); | |
if ($attachments): | |
foreach ($attachments as $attachment): | |
if(wp_attachment_is_image( $attachment->ID )): | |
// echo '<a href="'. wp_get_attachment_url($attachment->ID) . '">Text Link</a>'; | |
$POST_THUMBNAIL = wp_get_attachment_image( $attachment->ID, 'thumb-featured' ); | |
// var_dump( wp_get_attachment_image( $attachment->ID, 'thumb-featured' ) ); | |
break; | |
endif; | |
endforeach; | |
endif; | |
endif; | |
//if attachment is not set because using link due to import or whatever reason, parse and use first img link | |
if( empty( $POST_THUMBNAIL ) ): | |
// $post_content = get_post( $ID )->post_content; | |
global $post; | |
$post_content = $post->post_content; | |
$post_content = substr( $post_content, 0, 1300 ); | |
// var_dump( substr( $post_content, 0, 1000 ) ); | |
// echo "<br><br>"; | |
// $post_content = ''; | |
// var_dump( $post ); | |
if (preg_match('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $post_content, $matches)): | |
$src = $matches[1]; | |
@list($width, $height) = getimagesize($src); | |
$POST_THUMBNAIL = '<img src="' . $src . '" width="'.$width.'" height="'.$height.'" alt="' . get_the_title() . '" class="" />'; | |
// var_dump( $img ); | |
endif; | |
endif; | |
endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment