1

I want to get posts of a specific date, I tried the following code but I did not get the result what I wanted.

<?php
$mil = 1532996880000;
$seconds = $mil / 1000;
$dt = date( "Y-m-d", $seconds );

$post_by_date = $wpdb->get_row("
    SELECT * FROM {$wpdb->posts}
    WHERE post_date = $dt
    AND post_status = 'publish'
");

WP QUERY

$posts = get_posts(array(
    'post_type' => 'post',
    'date' => $dt,
    'posts_per_page' => 1
));

This did not work because, the output of $dt = 2018-07-31, but the output shows no results. Because it compares with 2018-07-31 09:09:40. So is there any way to get posts of a specific date?

5
  • This is pure PHP question, you an easily get 2018-07-31 from 2018-07-31 09:09:40 using PHP Aug 3, 2018 at 6:52
  • But if I use this method then I will have to compare each and every row in db and will have to get the date only.....this will take some amount of time
    – topper1309
    Aug 3, 2018 at 6:55
  • What do you plan to do with $post_by_date?
    – Max Yudin
    Aug 3, 2018 at 6:57
  • I just want the post data of a specific date and return the post data. Thats it! @MaxYudin
    – topper1309
    Aug 3, 2018 at 7:00
  • Can't it be done by wp-query? codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
    – user145078
    Aug 3, 2018 at 7:06

2 Answers 2

2
<?php
//  primarily get $year, $month and $day
$args = array(
    'date_query' => array(
        'year'  => $year,
        'month' => $month,
        'day'   => $day,
    )
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {

        // do whatever here

    }
}
1
  • Ok, I think this is the only way I can do it. Thank you Max
    – topper1309
    Aug 3, 2018 at 7:18
1

Please use date query for that also use below code hope it will work for you

$mil = 1532996880000;
$seconds = $mil / 1000;
$dt = date( "Y-m-d", $seconds );
 $year =  date( "Y", $seconds );
 $month =  date( "m", $seconds ); 
 $day =  date( "d", $seconds );


$args = array(
 'date_query' => array(
  array(
   'year'  => $year,
   'month' => $month,
   'day'   =>$day,
  ),
 ),
);
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    echo '<ul>';
    while ( $query->have_posts() ) {
        $query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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