NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Oct 01 2022
Estimated reading time : 1 minute, 26 seconds - 186 words
Share the post "WordPress: Display Posts of the Month with get_posts"
With this tutorial, we’ll show you how to use a query with the database so that it displays posts or Post Types that were published during any given month.
The get_posts is a great tool to search within a database but it can restrict the usable parameters. It can simplifies queries in any page template.
It also allows us to display a number of results via the post_per_page without pagination. We will need to make sure to close our query with
wp_reset_postdata();.
In our example below, we’ve configured posts_per_page to -1 because we want to display the current month only. Our Post Type is viavideos, so either replace it by your or ‘post’ for articles.
As you can see, we need to stock two different variables in the dates which represent the current month and year. Then with our parameters we need to do a date_query and add our two date parameters.
And then we close the loop to display our results.
Display Post or Post Type of the month with the get_posts function.
<?php $year = date('Y'); $month = date('m'); $args = array( 'posts_per_page' => -1, 'post_type' => 'viavideos', 'date_query' => array( array( 'year' => $year, 'month' => $month, ), ), ); $posts = get_posts( $args ); foreach( $posts as $post ) : setup_postdata($post); ?> <?php /// Votre div dynamique désirée ?> <?php endforeach; wp_reset_postdata(); ?>