
How To Display The Posts From Specific Category on WordPress
To display posts from a specific category on WordPress, you can use the WP_Query
function. Here are the steps:
- Determine the ID of the category you want to display. You can find this by going to Posts > Categories in your WordPress dashboard and hovering over the category name. The ID will appear in the URL at the bottom of your browser.
- Create a new WordPress loop that uses the
WP_Query
function to retrieve posts from the desired category. Here’s an example of what your code might look like:
<?php $category_id = 3; // Replace 3 with the ID of the category you want to display $query = new WP_Query( array( 'category__in' => $category_id ) ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); ?> // Display your post content here <?php }} wp_reset_postdata(); // Restore original post data ?>
In this example, we’re creating a new WP_Query object that retrieves all posts from the category with the ID of 3 (replace this with the ID of your desired category). Then, we’re using a standard WordPress loop to display the posts.
Note that we’re using the category__in parameter to specify the category ID. This allows us to display posts from multiple categories if we provide an array of category IDs instead of a single value.
Finally, we’re calling wp_reset_postdata() to restore the original post data, which ensures that subsequent loops or functions work correctly.