Add Snippet To Project
Are you looking for a way to display only the published posts on your WordPress website between two specific dates? In this article, we will guide you through the process of filtering and displaying posts based on a date range. Whether you want to create a temporary event page or showcase posts within a specific timeframe, this tutorial will provide you with the necessary steps to achieve it. Stay tuned to learn how to display published posts between two dates on your WordPress site.
function wpturbo_display_published_posts_between_dates($start_date, $end_date) {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'date_query' => array(
'after' => $start_date,
'before' => $end_date
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Output the post content or perform any other action
}
wp_reset_postdata();
}
}
add_action('init', 'wpturbo_display_published_posts_between_dates');
The provided code snippet demonstrates how to display published posts between two specific dates in WordPress.
The first part of the code defines a new function called wpturbo_display_published_posts_between_dates()
. This function takes two parameters: $start_date
and $end_date
, which represent the starting and ending dates respectively.
Within the function, we create an array called $args
that stores various parameters for the WP_Query object. These parameters specify the query requirements for fetching the published posts.
post_type
is set to'post'
to indicate that we want to retrieve posts.post_status
is set to'publish'
to ensure that only published posts are included in the query.date_query
is an array that specifies the date range with the'after'
and'before'
parameters set to$start_date
and$end_date
respectively.
After configuring the query parameters, we create a new instance of the WP_Query
class and pass in the $args
array to execute the query.
We then check if there are any posts returned by checking the condition $query->have_posts()
. If there are posts available, we iterate over each post using a while loop by calling $query->the_post()
. This sets up the necessary environment for using template tags to display the post content, metadata, etc.
Inside the loop, you can output the post content or perform any other actions you desire. For example, you can use template tags like the_title()
, the_content()
, or the_permalink()
to display the respective post elements.
After the loop, we call wp_reset_postdata()
to reset the global $post
variable and restore the main query context.
Finally, we hook the wpturbo_display_published_posts_between_dates()
function to the init
action using the add_action()
function. This ensures that the function is executed when WordPress initializes, allowing the published posts to be displayed within the specified date range.