I want to display the titles of the post of the same month as the blog post. I tried this ..

<?php $year = the_date('Y')?>
<?php $month = the_date('M')?>

      <?php  $theids = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND MONTH(post_date)= '".$month."' AND YEAR(post_date) = '".$year."' ORDER BY post_date ASC");
       foreach ($theids as $theid): ?>
        <?php echo $theid->post_title; ?>

       <?php endforeach; ?>

but it's returning nothing. How can I make it work? Thanks.

  • What does your sql query look like? When testing sql, you should place your query string in a variable, then echo/dump/log the variable to see what sql is being called. With that said, try a lower case m when getting the month, like the_date('m'). Upper case M returns the textual three letters like Jan - Dec Jun 15, 2016 at 23:04
  • tried the_date('m'), still not working Jun 15, 2016 at 23:07
  • If you echo the query, what do you get? Jun 15, 2016 at 23:08
  • See also my answer here, it's an handy function I made: wordpress.stackexchange.com/a/276929/10381 Aug 15, 2017 at 9:02

1 Answer 1


There is date_query which can handle this and an SQL query is not a good practice when you can take advantage of WordPress Query API:

$pid = 1; // post ID here

$args = array(
    'posts_per_page' => -1,
    'post_type' => 'post',
    'date_query' => array(
            'year'  => get_the_date('Y', $pid),
            'month' => get_the_date('m', $pid)

$posts = get_posts( $args );

print_r( $posts );

Hope that helps.

  • Is it necessary to define post id?
    – Omer
    Apr 13, 2017 at 14:54
  • @Omer not really, but you can replace the date functions with static dates: get_the_date('Y', $pid) as 2017 and get_the_date('m', $pid) as 04
    – Ismail
    Apr 14, 2017 at 10:03
  • can we also get post of the day or week like you are getting from year and month?
    – Omer
    Apr 14, 2017 at 22:25

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.