Last active
December 18, 2015 09:39
-
-
Save dsebao/5762560 to your computer and use it in GitHub Desktop.
Detect images attached to post - WordPress
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 | |
| //PASTE THIS IN FUNCTIONS | |
| function my_image($postid=0, $size='thumbnail') { //it can be thumbnail or full | |
| if ($postid<1){ | |
| $postid = get_the_ID(); | |
| } | |
| if(has_post_thumbnail($postid)){ | |
| $imgpost = wp_get_attachment_image_src(get_post_thumbnail_id($postid), $size); | |
| return $imgpost[0]; | |
| } | |
| elseif ($images = get_children(array( //If you upload an image function gets first image | |
| 'post_parent' => $postid, | |
| 'post_type' => 'attachment', | |
| 'numberposts' => '1', | |
| 'orderby' => 'menu_order', | |
| 'order' => 'ASC', //If reverse use DESC | |
| 'post_mime_type' => 'image', ))) | |
| foreach($images as $image) { | |
| $thumbnail=wp_get_attachment_image_src($image->ID, $size); | |
| return $thumbnail[0]; | |
| } | |
| } | |
| ?> |
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
| //In your template, where do you want to show the image of the post | |
| <?php while ( have_posts() ) : the_post();?> | |
| <article> | |
| <?php if(my_image($post->ID, 'thumbnail') != ''){?> | |
| <a href="<?php the_permalink();?>"> | |
| <img alt="<?php the_title();?>" title="<?php the_title();?>" src="<?php echo my_image($post->ID, 'thumbnail'); ?>"/> | |
| </a> | |
| <?php }?> | |
| </article> | |
| <?php endwhile;?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment