Matt
Matt

Reputation: 828

Last/most recent month of posts

I have a staff newsletter, where a monthly issue is published just before the month it refers to.

I need my index page to display the posts for the most recent month of posts.

For example: The current month is July, but the last month where anything was posted was May, so the index page should display Mays posts, until the next set of posts are published.

I was using:

$current_month = date('m');
$current_year = date('Y');
query_posts("year=$current_year&monthnum=$current_month&order=DESC")

But this would only show posts for the current month, so the index page is now blank, due to there being no posts for the current month.

Any thoughts on how I can resolve this?

Thanks

Upvotes: 0

Views: 2855

Answers (2)

Matt
Matt

Reputation: 828

Got it

$lastpost = strtotime(get_lastpostdate());
$lastmonth = date('m', $lastpost);
$lastyear = date('Y', $lastpost);

$args=array(
      'post_type' => 'post',
      'post_status' => 'publish',
      'year'=>$lastyear,
      'monthnum'=>$lastmonth,
      'order'=>'DESC',
      'posts_per_page' =>10
);

query_posts($args);

I converted the get_lastpostdate() to a timestamp and the got the year and month from that timestamp

Upvotes: 1

Ravi Patel
Ravi Patel

Reputation: 5211

Use this query to display most recent last month post:

<?php 
$today = getdate();
$args=array(
      'post_type' => 'post',
      'post_status' => 'publish',
      'year'=>$today["year"],
      'monthnum'=>$today["mon"]-1,
      'order'=>'DESC',
      'posts_per_page' =>10
);

query_posts($args);
?>

<?php while ( have_posts() ) : the_post(); ?>
    <H1><?php echo the_title(); ?></H1>
<?php endwhile; ?>

Upvotes: 2

Related Questions