0

I need to edit my Wordpress child theme (based on Twenty Twenty One) archives.php template so that it grabs the first image added within any Post, not the Featured Image as that is being used by another plugin (and as such has to be different dimensions than what we want here). I've tried a few different solutions but nothing seems to work, I am guessing this may be to do with the fact I am using Gutenberg blocks.

I did however get the following code to work for the posts I had already uploaded (I have set out the most relevant line of code between two spaces within the archiveContainer div), but bizarrely after then creating some new test posts the code is no longer working and is just grabbing the Featured Images again, which is not what we want.

    <?php while ( have_posts() ) : ?>
    <?php the_post(); ?>

    <?php $attachment = array_values( get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'numberposts'  => 1 ) ) ); ?>
    <h2 class="archiveTitle" id="post-<?php the_ID(); ?>">
        <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
    </h2>
    <div class="archiveContainer">
        
        
        
        <?php if( $attachment ) echo '<img src="' . wp_get_attachment_url($attachment[0]->ID) . '" class="post-attachment" />'; ?>
        
        
        
    </div>
    <?php get_template_part( 'template-parts/content/content', get_theme_mod( 'display_excerpt_or_full_post', 'excerpt' ) ); ?>
<?php endwhile; ?>

It could well be that I have inadvertently changed or deleted something of course - but, any ideas how I can get this working consistently?

NPC
  • 25
  • 6
  • If you need the same image as the featured image, just in a different size - then you should get the _id_ of the feature image, and use `wp_get_attachment_image` to get it returned in a different size ... – CBroe Sep 27 '21 at 09:02
  • Ah, thank you @CBroe however I should have made it more clear, we actually do just want to grab the first image of any post, which will be different than the Featured Image, its not just that we want the same image but in a different size. – NPC Sep 27 '21 at 09:09

0 Answers0