A custom WordPress plugin that creates a custom post widget with a category filter, allowing users to display a specified number of posts and filter them by category. It uses a shortcode to generate a list of posts with a dropdown menu for category selection, dynamically updating the displayed posts based on the selected category.
<?php
/*
Plugin Name: Custom Post Widget
Description: A custom post widget with category filter.
Version: 1.0
Author: Karishma KK
*/
function custom_post_widget_shortcode( $atts ) {
$atts = shortcode_atts(
array(
'posts_per_page' => 6,
), $atts, 'custom_post_widget'
);
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => $atts['posts_per_page'],
'post_type' => 'post',
'paged' => $paged,
);
// Check if category filter is applied
if ( isset( $_GET['category'] ) && $_GET['category'] != 'all' ) {
$args['category_name'] = sanitize_text_field( $_GET['category'] );
}
$query = new WP_Query( $args );
$output = '<div id="custom-post-widget">';
$output .= '<label><strong>Filter</strong></label>';
$output .= '<select id="category-filter">';
$output .= '<option value="all">All Categories</option>';
$categories = get_categories();
foreach ( $categories as $category ) {
$selected = ( isset( $_GET['category'] ) && $_GET['category'] == $category->slug ) ? 'selected' : '';
$output .= '<option value="' . $category->slug . '" ' . $selected . '>' . $category->name . '</option>';
}
$output .= '</select>';
$output .= '<div id="posts-container">';
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$output .= '<article class="post">';
if ( has_post_thumbnail() ) {
$output .= '<div class="post-image">' . get_the_post_thumbnail( get_the_ID(), 'thumbnail' ) . '</div>';
}
$output .= '<h2 class="post-title"><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';
$output .= '<div class="post-excerpt">' . get_the_excerpt() . '</div>';
$output .= '</article>';
}
wp_reset_postdata();
} else {
$output .= '<p>No posts found.</p>';
}
$output .= '</div></div>';
$output .= '<script>
document.addEventListener("DOMContentLoaded", function() {
var categoryFilter = document.getElementById("category-filter");
categoryFilter.addEventListener("change", function() {
var selectedCategory = this.value;
var baseUrl = "' . home_url('/blog-revamp') . '";
var url = baseUrl + (selectedCategory !== "all" ? "?category=" + selectedCategory : "");
window.location.href = url;
});
});
</script>';
return $output;
}
add_shortcode( 'custom_post_widget', 'custom_post_widget_shortcode' );
The shortcode is [custom_post_widget]. This shortcode can be inserted into a WordPress post or page to display the custom post widget with the category filter.