0
0
Wordpressframework~30 mins

WP_Query class in Wordpress - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the WP_Query Class to Display Recent Posts
📖 Scenario: You are building a WordPress theme and want to show a list of recent blog posts on the homepage.
🎯 Goal: Create a custom query using the WP_Query class to fetch the 5 most recent posts and display their titles in an unordered list.
📋 What You'll Learn
Create a WP_Query object with parameters to get 5 recent posts
Store the query parameters in a variable called $args
Use a while loop with $query->have_posts() and $query->the_post()
Output the post titles inside <li> tags within a <ul>
Reset post data after the loop with wp_reset_postdata()
💡 Why This Matters
🌍 Real World
Displaying recent or filtered posts on WordPress theme pages or widgets.
💼 Career
Essential skill for WordPress theme and plugin developers to customize content display.
Progress0 / 4 steps
1
Set up the query parameters
Create an array called $args with a key 'posts_per_page' set to 5 to specify fetching 5 posts.
Wordpress
Need a hint?

Think of $args as a list of instructions for which posts to get.

2
Create the WP_Query object
Create a new WP_Query object called $query using the $args array.
Wordpress
Need a hint?

This creates the query that will fetch the posts based on your parameters.

3
Loop through the posts and display titles
Use a while loop with $query->have_posts() and inside it call $query->the_post(). Inside the loop, output each post title inside an <li> tag using get_the_title().
Wordpress
Need a hint?

Remember to open the list before the loop and close it after.

4
Reset post data after the loop
After the loop, call wp_reset_postdata() to restore the original post data.
Wordpress
Need a hint?

This step ensures WordPress returns to the main query after your custom loop.