• alexduff

    (@alexduff)


    I really would appreciate help with the following. I have added a template which collates pupil posts which is working great. However, I also want to add a second template which does the same but within a set timeframe – e.g., only display posts from January to June 2011. This would allow me to ‘freeze a report in time’.

    This code does not work as I hoped it would:

    $args = array( 'numberposts' => 3, 'tag'=> "mathtag", 'year' => 2011,'monthnum' => 1,2,3,4,5,6);
    $postsByTag = get_posts($args);

    The monthnum part does not work. Replacing it with a single digit does work, but I need posts from across multiple months.

    I also tried

    $postsByTag = get_posts('tag=mathtag&numberposts=3&year=2011&monthnum=1,2,3,4,5,6');

    but again this did not work. Any idea how I can select posts from across a range of months?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Have you tried the date range example here: https://codex.www.ads-software.com/Class_Reference/WP_Query#Time_Parameters

    get_posts() makes use of the WP_Query class to fetch posts.

    Thread Starter alexduff

    (@alexduff)

    keesiemeijer – sincere thanks for this!!!! You’ve helped direct me to a perfect solution which I will enter below in case anyone else might be trying to do this too.

    Firstly, we need this function defined early on in the template:

    function filter_where( $where = '' ) {
    	// posts for January 2009 to July 10th, 2012
    	$where .= " AND post_date >= '2009-01-01' AND post_date < '2012-07-10'";
    	return $where;
    }

    Then this code can be used to extract posts inside the timeframe set in the function above:

    <?php
    global $post;
    
    add_filter( 'posts_where', 'filter_where' );
    
    $the_query = new WP_Query( array('tag' => 'mathtag', 'numberposts' => 3 ));
    $postsByTag = get_posts('tag=mathtag&numberposts=3');
    
    while ( $the_query->have_posts() ) : $the_query->the_post();
    
    echo '<a href="'. get_permalink().'">*</a> [';
    echo the_time('d/m/y').']  '.get_the_excerpt().'</a><br />';
     endwhile;?>
    <?php remove_filter( 'posts_where', 'filter_where' );?>
    Moderator keesiemeijer

    (@keesiemeijer)

    You’re welcome. Glad you got it resolved

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Needing to show archived posts from multiple months’ is closed to new replies.