Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Stephen O'Connor
Stephen O'Connor
22,291 Points

WordPress Latest News Page Showing Custom Fields From All News Stories

I have my own custom WordPress theme and I am building out the 'Latest News' section at the moment. I have a custom field for my page header image and alt tag for each page on my site, I am using the following code to display those custom fields on each page:

<section class="page-heading">
      <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
            <img src="<?php the_field( 'header_image' ); ?>" alt="<?php the_field( 'main_header_image_alt_tag' ); ?>">
      <?php endwhile; endif; ?>
</section>

Which works fine. But on my 'Latest News' page all the custom fields from all the news stories (posts) are being displayed and not the header image I have chosen for that page, so for example if I have 3 post displayed per page then I am getting 3 images and 3 alt tags displayed.

In my settings I have my 'Posts Page' set to 'Latest News'.

Is there a way I can only have 1 image and 1 alt tag displayed and not all 3?

Thanks.

2 Answers

Zac Gordon
STAFF
Zac Gordon
Treehouse Guest Teacher

Sounds like you need two queries here, one that pulls in the page content and one that loops through the stories? Not sure how you are pulling in header images.

Stephen O'Connor
Stephen O'Connor
22,291 Points

Hi Zac,

Thanks for your response. The page header images are coming for a custom field I have set up and when I publish the page(s) I choose the header image then add the alt tag.

This works fine for all my pages but the 'Latest News' page where the header image for the page doesn't display but the header images from the news stories do. So for example if I have my posts per page set to 5, 5 images would display. I have my 'posts page' set to 'Latest News' in my reading settings in the admin.

All my other pages display the header image as expected, just not the 'Latest News' page.

Stephen O'Connor
Stephen O'Connor
22,291 Points

I managed to get around this by unsetting my posts page in my reading settings and creating a new template for my latest news page and using WP_Query to bring in the page data and latest posts.

I'm not sure if this is the best way to go about this but it seems to have worked for my situation.