Methods for Including Specific Category Posts on WordPress Homepage
In WordPress theme development, you may need to display posts from specific categories on the homepage or exclude certain categories. Here are implementation methods for two common scenarios.
1. Display Latest Posts from a Specific Category
You can use the query_posts() function to modify the main query and retrieve posts from a particular category. The following code example fetches the 10 latest posts from category ID 15 and displays them as a list.
<ul>
<?php
query_posts('cat=15&posts_per_page=10');
while (have_posts()) : the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
wp_reset_query();
?>
</ul>
Parameter Explanation:
cat=15: Specifies category ID 15.posts_per_page=10: Limits display to 10 posts.
Important Note: query_posts() completely overrides the main query, which may affect pagination and page logic. For plugin or theme development, using WP_Query or get_posts() for secondary queries is recommended.
2. Exclude Specific Categories from Homepage
To exclude posts from certain categories in the main loop on the homepage (index.php), modify query parameters before the loop starts. This code excludes posts from category IDs 5 and 6.
<?php
if (have_posts()) :
query_posts($query_string . '&cat=-5,-6');
while (have_posts()) : the_post();
// Loop content
endwhile;
endif;
?>
Parameter Explanation:
cat=-5,-6: Prefixing category IDs with a minus sign-excludes them.$query_string: Preserves existing query variables (e.g., pagination parameters).
Implementation: Locate the main loop in your theme's index.php file (typically starting with <?php while (have_posts()) : the_post(); ?>) and replace it with the code above.
Better Practice: Use WP_Query
Since query_posts() interferes with the global $wp_query object, it can cause unintended side effects (e.g., pagination errors, incorrect sidebar data). Modern WordPress development recommends using WP_Query for custom queries.
Example: Using WP_Query to Display Category Posts
<ul>
<?php
$custom_query = new WP_Query(array(
'cat' => 15,
'posts_per_page' => 10
));
if ($custom_query->have_posts()) :
while ($custom_query->have_posts()) : $custom_query->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
wp_reset_postdata(); // Reset post data
endif;
?>
</ul>
This method doesn't affect the main query and is more reliable.
Summary and Considerations
- Define Requirements: Determine whether to include or exclude categories.
- Choose Method: Use
query_posts()for simple main loop modifications, but preferWP_Queryfor independent loops. - Clean Up Resources: Always call
wp_reset_query()afterquery_posts()andwp_reset_postdata()afterWP_Query. - Performance: Avoid executing too many complex queries on a single page.
Using these methods, you can flexibly control post display logic on your WordPress homepage or any page.