Are you looking for a way to get the first image from your blog post and display it in any size? While there’s probably a plugin for this, we have created a quick code snippet that you can use to return the first image attachment from a post as a thumbnail in WordPress.
Instructions:
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
function first_img($size="thumbnail") { $files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image'); if($files) : $keys = array_reverse(array_keys($files)); $num = $keys[0]; $image_attributes = wp_get_attachment_image_src( $num, $size ); echo '<img src="'.$image_attributes[0].'" width="'.$image_attributes[1].'" height="'.$image_attributes[2].'" class="firstimg" />'; endif; }
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 9 best WordPress auction plugins to build the next eBay and how to use Google Optimize in WordPress.
Comments Leave a Reply