I’m trying to make a couple of Page Templates for different Pages that should act as an archive to display posts (a Custom Post Type actually) in a certain date range.

The website it concerns is http://memstories.com and the CPT is “Events”. I already found some mentions of a thread on WP Support (https://wordpress.org/support/topic/show-the-posts-published-before-a-specific-date?replies=2#post-1066144), but I cannot get it to work:

<?php
function filter_where($where="") {
$where .= " AND post_date >= '1900-01-01' AND post_date <= '1949-12-31'";
return $where;
}
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>

Because the Event posts on this website are all historic events, I’m using the Published Date as the actual date a historic event happened and I’m going as far back as the year 1900. In the above query I’m trying to accomplish a list of posts that fit within the date range of the first half of the 20th century (1900 – 1949), but it’s a fail any way I try it.

There really isn’t anywhere else I can find more information, in fact all similar questions on stackexchange are answered with a link to the exact same thread (5 years old!) on WordPress Support.

Anyone have an idea how to work this out?

2 Answers
2

Saving the date in post meta is a slightly more sane approach, the post_date column was not designed with your use case in mind. You may get weird results with dates before the Unix epoch (January 1, 1970). Then it’s just a simple meta_query to load posts between dates, no filter necessary.

$start="1900-01-01";
$end = '1949-12-31';
$args = array(
    'post_type' => 'events',
    'posts_per_page' => -1,
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'meta_key' => '_event_date',
    'meta_query' => array(
        array(
            'key' => '_event_date',
            'value' => array( $start, $end ),
            'compare' => 'BETWEEN',
            'type' => 'DATE'
        )
    )
);
$events_query = new WP_query( $args );

Leave a Reply

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