0

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.

4
  • 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 – czerspalace Jun 15 '16 at 23:04
  • tried the_date('m'), still not working – Malek Zalfana Jun 15 '16 at 23:07
  • If you echo the query, what do you get? – czerspalace Jun 15 '16 at 23:08
  • See also my answer here, it's an handy function I made: wordpress.stackexchange.com/a/276929/10381 – Luca Reghellin Aug 15 '17 at 9:02
3

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(
        array(
            'year'  => get_the_date('Y', $pid),
            'month' => get_the_date('m', $pid)
        ),
    ),
);

$posts = get_posts( $args );

print_r( $posts );

Hope that helps.

3
  • Is it necessary to define post id? – Omer Apr 13 '17 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 '17 at 10:03
  • can we also get post of the day or week like you are getting from year and month? – Omer Apr 14 '17 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.