How to display WP post with category filter option?
We can use shortcode function to display post with category filter option. You have to add this function to functions.php . Here is the demo code
function posts_with_category_filter_shortcode($atts) {
// (you can customize default values here)
$atts = shortcode_atts(array(
'posts_per_page' => 4, // Number of posts to display
), $atts, 'category_filter_posts');
// Get categories for the filter dropdown
$categories = get_categories();
// Get selected category from the URL parameter (if available)
$category_filter = isset($_GET['category']) ? $_GET['category'] : '';
// Query posts based on selected category
$args = array(
'posts_per_page' => $atts['posts_per_page'],
'orderby' => 'date',
'order' => 'DESC',
'cat' => $category_filter,
);
if (!empty($category_filter)) {
$args['category'] = $category_filter;
}
$query = new WP_Query($args);
// Start the output buffer to capture HTML content
ob_start();
// Display filter form (category dropdown)
echo '<form method="GET" action="">';
echo '<select name="category" onchange="this.form.submit()">';
echo '<option value="">All Categories</option>';
foreach ($categories as $category) {
$selected = ($category->term_id == $category_filter) ? 'selected' : '';
echo '<option value="' . $category->term_id . '" ' . $selected . '>' . $category->name . '</option>';
}
echo '</select>';
echo '</form>';
// Display posts
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo '<div class="post-item">';
echo '<h2>' . get_the_title() . '</h2>';
echo '<p>' . get_the_excerpt() . '</p>';
echo '<a href="' . get_permalink() . '">Read More</a>';
echo '</div>';
}
} else {
echo '<p>No posts found in this category.</p>';
}
wp_reset_postdata();
// Return the captured HTML content
return ob_get_clean();
}
add_shortcode('category_filter_posts', 'posts_with_category_filter_shortcode');
Use this shortcode [category_filter_posts] for display the post and category filter option in your page.
2 Comments
Willard
February 8, 2025Wonderful blog! I found it while searching on Yahoo News.
Do you have any tips on how to get listed in Yahoo News?
I’ve been trying for a while but I never seem to get there!
Thanks
Anirban Poddar
February 10, 2025Thank you