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

Displaying a Recent Blog Post on "front-page.php"

Hi everyone!

I have a problem that I just can't find any resources on how to do something with WordPress. All I want to know is how to display a recent blog post to the 'front-page.php'. I have gone through pages and pages on Google. I did manage to come across something that I was after, but all it is doing is displaying all the blog posts on the site.

I am using a grid and a PHP loop to write display 3 of my recent posts (see code below).

``php

<div class="row">

<?php

$the_query = new WP_Query( 'posts_per_page = 1' ); 


while ($the_query -> have_posts()) : $the_query -> the_post();

for( $productCounter = 0; $productCounter <= 3; $productCounter++ ) {

    echo '<div class="col-4 blog-post-listing">';
        echo '<h4><small>'; the_date(); echo '</small></h4>';
        echo '<h3><a href="'; the_permalink(); echo '">'; the_title(); echo'</a></h3>';
        echo '<p>'; the_excerpt(); echo'</p>';
        echo '<a role="button" class="btn-clear-small" href="'; the_permalink(); echo '">'; echo'Read more</a></h3>';
    echo '</div>';

}

endwhile; wp_reset_postdata();

?>

</div><!-- /.row -->

I hope that I am making sense and I'd appreciate any help or advice on how I can achieve this, cause this problem is kicking my butt!

Many thanks

Stu :)

2 Answers

Stanley Thijssen
Stanley Thijssen
22,831 Points

Hi Stu,

Can you try the following code:

$the_query = new WP_Query( array(
     'post_type' => 'post',
     'posts_per_page' => 1,
  )
);

if ($the_query -> have_posts()) : while ($the_query -> have_posts()) : $the_query -> the_post();

// Do something with this data;

endwhile; endif; wp_reset_postdata();

Hi there Stanley,

Sorry for my late response, I never got a notification saying you had posted a reply.

I've tried your code out and it is working perfectly! Thank you so much :D