1

I have a Wordpress blog site that I am building. My problem is that when the homepage loads it shows my earliest post from three years ago. What I would like it for my most recent post to show instead. Can anyone tell me how I could accomplish this. I have looked through several articles and none have a solution that work for me. Here is the code I am using to load the post:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h4>Posted on <?php the_time('F jS, Y') ?></h4>
<p><?php the_content(__('(more...)')); ?></p>
<hr> <?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p><?php
endif; ?>
2
  • 1
    You will most probably need to look for a pre_get_posts action which is altering the main query on your homepage, either in your theme or in a plugin you are using. Jun 8, 2016 at 12:31
  • Also, make sure that you do not have sticky posts set. Sticky posts will always appear as first posts on the homepage. Jun 8, 2016 at 12:38

1 Answer 1

-4

There must be something playing with your query (using pre_get_posts) as the default in WP is to load the last created post.

Use this WP_Query instead

$the_query = new WP_Query( 'posts_per_page=1&post_type=post' );
if ( $the_query->have_posts() ) {
 while ( $the_query->have_posts() ) {
    $the_query->the_post();
    ?>
    <h4>Posted on <?php the_time('F jS, Y') ?></h4>
    <p><?php the_content(__('(more...)')); ?></p>
    <?php
 } else {
  ?>
    <p><?php _e('Sorry, no posts matched your criteria.'); ?></p><?php
  <?php
}
wp_reset_postdata();
5
  • 1
    NOOOOOOOO!!!!!!, why do you want to do that. NEVER change the main query with custom one. This is a horrible solution which you should avoid. Sort the root of the issue, don't hide it with something which will later cause bigger issues Jun 8, 2016 at 12:35
  • depends on what the ultimate goal is surely Peter? this solution gives them more scope to customise to get the post from a certain category, or to change other aspects of the query ..... Jun 8, 2016 at 12:40
  • @GarethGillman Then WP should remove its default query and ask everyone to build their query :P
    – Sumit
    Jun 8, 2016 at 12:41
  • This is bad solution why because some plugin/theme adding something and we are removing it. If we don't want it then why to add ?
    – Sumit
    Jun 8, 2016 at 12:43
  • 1
    For every goal, there is pre_get_posts to alter the main query to suit your exact needs. There is even the posts_clauses filters which you can use to customize the main query. A custom query will never be solution as it runs extra unnecessary db queries, slows your page and ultimitely cause paging issues Jun 8, 2016 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.