2

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?

  • use of query_posts should be avoided in favour of WP_Query. see answer from @Milo – karpstrucking Feb 17 '15 at 21:10
3

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 );
  • Hmm that does seem to make more sense. I'll give it a try! – dbj Feb 18 '15 at 13:10
1

Well, WP may be suppressing your filter.

Per the WP Codex on posts_where @: http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where

Certain functions which retrieve posts do not run filters, so the posts_where filter functions you attach will not modify the query. To overcome this, set suppress_filters to false in the argument array passed to the function.

This is the code they reference:

//get posts AND make sure filters are NOT suppressed
$posts = get_posts( array( 'suppress_filters' => FALSE ) );

Are you using this on your get_posts() call ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.