wordpress theme get first attachment img function
wordpress functions feilong 20101121 ~ 20101121 646How to get first attachment img in a wordpress theme files eg index.php?Here feilong give you one resolution.
<?php //feilong get first attach <img> used in a loop 20101121 shenzhen $args = array( 'order' => 'ASC', 'post_type' => 'attachment', 'post_parent' => $post->ID,//feilong for current post in a loop 'post_mime_type' => 'image', 'post_status' => null, 'numberposts' => 1, );$attachments = get_posts($args);if ($attachments) { $feilong_attach_first_img = wp_get_attachment_image($attachments[0]->ID, 'thumbnail', false); } ?> <?php echo $feilong_attach_first_img; ?>
Of course,you can put it in functions.php too.Then use this function somewhere in your theme.
<?php //in functions.php feilong get first attachment <img> function feilong_get_attach_first_img($postid,$size='thumbnail') { $args = array( 'order' => 'ASC', 'post_type' => 'attachment', 'post_parent' => $postid, 'post_mime_type' => 'image', 'post_status' => null, 'numberposts' => 1, );$attachments = get_posts($args);if ($attachments) { $feilong_attach_first = wp_get_attachment_image($attachments[0]->ID, $size, false); return $feilong_attach_first;} } //then somewhere in your loop of wordpress theme echo $feilong_get_attach_first_img($post->ID); ?>
There are other ways to display wordpress attachment.Perhaps wp_get_attachment_image_src() is a more free wordpress function for you to code and resolve attachment problems.For more,contact me.
