Abdullah Alhutami
Abdullah Alhutami

Reputation: 25

Compare Post Meta Wordpress to Date

I have a meta_key as listing_expiry_date and its storing date (e.g. 2017-11-30 12:25:57). I believe its storing date as string as the meta_value field in the database is longtext

Now. I would like to get post array for posts that are expiring in one day. the code that I have developed is as follows.

$today = date('Y-m-d H:i:s')+1;

$args = array('posts_per_page' => $show, 

        'post_type' => $type, 'orderby' => $orderby, 'order' => $order, 'paged'  => $paged,

        'meta_query' => array (

                array (

                    'key' => 'listing_expiry_date',                                                             

                    'orderby' => 'meta_value',                       

                    'compare' => '<=',

                    'value' => $today,

                    'type'=> 'date'         
                )

              ) 

         );

This code works sometimes and sometimes I am getting posts that have expiry date of 3 and 5 and 7 days. I do not really know what is wrong.

Also, I would appreciate if you someone would help and show me how to display posts that have one hour remaining only.

Thanks guys.

Upvotes: 1

Views: 545

Answers (1)

Ankita Tanti
Ankita Tanti

Reputation: 455

Try below code :

$one_day_expiry = date('Y-m-d H:i:s', strtotime($date .' +1 day'));
$one_hour_expiry = date('Y-m-d H:i:s', strtotime($date .' +1 hour'));

$args = array(
                'posts_per_page' => $show, 
                'post_type' => $type, 
                'orderby' => $orderby, 
                'order' => $order, 
                'paged'  => $paged,
                'meta_query' => array (
                                        'relation' => 'AND',
                                        array (
                                                'key' => 'listing_expiry_date',                       
                                                'compare' => '<=',
                                                'value' => $one_day_expiry,
                                                'type'=> 'date'         
                                            )

                                    ) 

             );

The mistake you were doing was at generating next day's date. for getting posts expiring in next one hour try replacing $one_day_expiry variable with $one_hour_expiry variable in meta query.

Hope this will help you.

Upvotes: 0

Related Questions