Skip to content

Instantly share code, notes, and snippets.

@Maden-maxi
Created December 6, 2016 09:56
Show Gist options
  • Save Maden-maxi/d1885bbbcc4f11d389bd834a996849a4 to your computer and use it in GitHub Desktop.
Save Maden-maxi/d1885bbbcc4f11d389bd834a996849a4 to your computer and use it in GitHub Desktop.
Getting post attachment image if thumbnail not defined
function sunset_get_attachment( $num = 1 ){
$output = '';
if( has_post_thumbnail() && $num == 1 ):
$output = wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) );
else:
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => $num,
'post_parent' => get_the_ID()
) );
if( $attachments && $num == 1 ):
foreach ( $attachments as $attachment ):
$output = wp_get_attachment_url( $attachment->ID );
endforeach;
elseif( $attachments && $num > 1 ):
$output = $attachments;
endif;
wp_reset_postdata();
endif;
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment