سؤال

I'm seeking to customize my categories listing (archive.php) so that it shows a thumbnail image of the first image attached to each post

However, apparently the archive.php file is one of those that does not natively support the attachment object. For example, the code below will do most of what I want (though if no attachment is found, I get a blank image, I need to fix that).

However, I'm afraid having a SELECT in a loop like this is perhaps way too expensive for what I'm trying to do.

Any ideas?

    <?php while (have_posts()) : the_post(); ?>
    <?php global $wpdb; $attachment_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_parent = '$post->ID' AND post_status = 'inherit' AND post_type='attachment' ORDER BY post_date DESC LIMIT 1"); ?>
        <div class="searchItem" style="clear:both;">
            <h3 id="post-<?php the_ID(); ?>"><img src="<?php echo wp_get_attachment_url($attachment_id); ?>" class="post-attachment" /><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
            <small><?php the_time('l, F jS, Y') ?></small>
            <div class="excerpt"><?php echo $post->post_excerpt; ?></div>
            <div class="postmetadata">Posted in <?php the_category(', ') ?> | <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></div>
        </div>
    <?php endwhile; ?>
هل كانت مفيدة؟

المحلول

You could use the WordPress function get_children. Although I don't think it makes a difference, performance-wise.

<?php while (have_posts()) : the_post(); ?>
    <?php $attachment = array_values( get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'numberposts'  => 1 ) ) ); ?>
    <div class="searchItem" style="clear:both;">
        <h3 id="post-<?php the_ID(); ?>">
        <?php if( $attachment ) echo '<img src="' . wp_get_attachment_url($attachment[0]->ID) . '" class="post-attachment" />'; ?>
        <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
        <small><?php the_time('l, F jS, Y') ?></small>
        <div class="excerpt"><?php echo $post->post_excerpt; ?></div>
        <div class="postmetadata">Posted in <?php the_category(', ') ?> | <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></div>
    </div>
<?php endwhile; ?>

نصائح أخرى

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى wordpress.stackexchange
scroll top