Reputation: 11
I have this custom post type Gallery. I want to call first image from the posts.
<?php
$item_count = 1;
$args = array( 'post_type' => 'gallery', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
$item_count = 1;
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php the_title(); ?>
<div class="count"><?php echo $item_count; ?></div>
<div class="thumbnail">
// THE FIRST GALLERY ATTACHMENT IMAGE
</div>
<?php $item_count++; ?>
<?php endwhile; ?>
Any ideas?
Note: I added Gallery no simple image on the post!
Upvotes: 1
Views: 2237
Reputation: 6359
Check this WordPress Codex example.
The code will show the first image associated with the post.
Or check this WordPress forum discussion that also deals with this problem.
UPDATE:
Go to Appearance > Editor and select Theme functions (functions.php). at the end of the file add this:
// Get URL of first image in a post
function catch_that_image($my_postid) {
global $post;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', get_post_field('post_content', $my_postid), $matches);
$first_img = $matches [1] [0];
// no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
} ?>
Now in your code you modify this part of the code:
<div class="thumbnail">
<?php echo catch_that_image($loop->ID) ?>
</div>
UPDATE V2
I modified the code to suit your code.
UPDATE V3
I tried the code on my development site and I modified it further until the code worked as it should. You should not have any problems now.
Upvotes: 1