Pregunta

Estoy buscando personalizar mi listado de categorías (Archive.php) para que muestre una imagen en miniatura de la primera imagen adjunta a cada publicación

Sin embargo, aparentemente el archivo Archive.php es uno de los que no admite de forma nativa el objeto de archivo adjunto. Por ejemplo, el siguiente código hará la mayor parte de lo que quiero (aunque si no se encuentra ningún archivo adjunto, obtengo una imagen en blanco, necesito solucionarlo).

Sin embargo, me temo que tener una selección en un bucle como este es quizás demasiado caro para lo que estoy tratando de hacer.

¿Algunas 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; ?>
¿Fue útil?

Solución

Puede usar la función de WordPress get_children. Aunque no creo que haga una diferencia, en cuanto al rendimiento.

<?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; ?>

Otros consejos

WP tiene una función central para ver esto, ver mi publicación http://wpengineer.com/1735/easier-better-solutions-to-get-pictures-on-your-posts/

Licenciado bajo: CC-BY-SA con atribución
scroll top