2

I am trying to loop through all the post to get the top most shared posts on social network. I want to use the date_query parameter in the WP_query to get the posts of last two days , last 5 days, last 7 days and last 9 days. How can i implement it through using the date_query in WP_Query My WP_query is

<?php
 $args = array(
  'post_type' => 'post',
  'order'=>'DESC',
  'posts_per_page' => 1,
  'date_query' => array(
                     array(
        'after'     => '10 days ago',
        'inclusive' => true,
       ),
     ),
  'orderby'=>'meta_value',
  'meta_key'=>'esml_socialcount_TOTAL'
  );
 $the_query = new WP_Query($args);
 if($the_query->have_posts()) { 
 while ($the_query->have_posts()){$the_query->the_post();
?>
7

Here are two ideas for your date_query part:

1) After 2 days ago:

If you need posts published after current time, 2 days ago:

'date_query' => array(
     array(
         'after'     => '2 days ago',  // or '-2 days'
         'inclusive' => true,
     ),
 ),

then the corresponding SQL part is:

 post_date >= '2014-09-09 17:57:15'

if the current date-time is 2014-09-11 17:57:15.

2) After midnight 2 days ago :

If you need posts published after midnight, 2 days ago:

'date_query' => array(
     array(
         'after'     => 'midnight 2 days ago',
         'inclusive' => true,
     ),
 ),

then the corresponding SQL part is:

 post_date >= '2014-09-09 00:00:00'

if the current date-time is 2014-09-11 17:57:15.

You can than easily modify this to other day periods.

  • As i am placing this code , nothing is working , it didn't show my any posts , but as i change it to "before" instead of "after" in the array , it show the data , but the data which is output by this query is not correct – Harman Preet Sep 17 '14 at 10:15
  • Hi, do you have posts published during that period? – birgire Sep 17 '14 at 10:24
  • i publish the posts within last two days , last 7 days and even i change the time duration to max, but no result – Harman Preet Sep 17 '14 at 10:26
  • i have updated the question , kindly have a look on my parameters of wp_query – Harman Preet Sep 17 '14 at 10:32
  • Can you post the SQL query? $q = new WP_Query( $args ); echo $q->request; – birgire Sep 17 '14 at 10:32

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.