12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Jul 19, 2020

How to alter the Homepage Query to show the Latest Post

Sridhar Katakam

Updated on 1 Mar 2024

In a customization task I recently worked on, the requirement was to show one latest post on the homepage with its comments handled by wpDiscuz.

While <?php comments_template(); ?> inside a custom WP_Query loop on the homepage does show the comments section it will not be parsed by wpDiscuz since that plugin is only designed to work on individual Pages or Posts.

Enabling wpDiscuz on Home Page in the plugin's settings and enabling comments for the Page (set as static front page) will show wpDiscuz comments on the front page but they will be attached to the static front page itself rather than to the Post. See this support topic for more info.

The workaround to solve this problem is to alter the main query of the homepage by replacing the query with that of the latest post using pre_get_posts.

Let's see how this can be done in this premium tutorial.

Step 1

Set a Page as static front page at Settings > Reading.

Even though this Page will not be used for the homepage, this step is needed.

Step 2

Install and activate Code Snippets.

Add a new Snippet.

Title: Change the query of homepage to the latest post

Code:

This is a premium members-only content.

To view the rest of the content, please sign up for membership ($47/month or $599 one-time).

Already a member? Log in below or here.

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right