How to filter posts in WordPress monthwise

To filter posts in WordPress monthwise, you can use the built-in functions provided by WordPress to retrieve posts based on specific criteria.

get_header();

// Get the current month and year
$current_month = get_query_var('monthnum');
$current_year = get_query_var('year');

// Arguments for the query
$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'year' => $current_year,
    'monthnum' => $current_month,
);

// Query the posts
$posts_query = new WP_Query($args);

// Display the posts
if ($posts_query->have_posts()) :
    while ($posts_query->have_posts()) :
        $posts_query->the_post();
        ?>
        <h2><?php the_title(); ?></h2>
        <?php the_content();
    endwhile;
else:
    echo 'No posts found.';
endif;

get_footer();

Leave a comment

Your email address will not be published. Required fields are marked *