Get_posts not older than X days - Wordpress

On my Wordpress site, I use this get_posts code:

get_posts( array ( 'numberposts' => 5, 'orderby'=>'comment_count', 'order'=>'DESC', 'post_type' => array ( 'post' ) ) 

How do I filter it so messages are not older than 10 days? Therefore, it should only post messages from the last 10 days.

+6
source share
2 answers

Starting with version 3.7 you can use date_query http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

So it will look like this:

 $args = array( 'posts_per_page' => 5, 'post_type' => 'post', 'orderby' => 'comment_count', 'order' => 'DESC', 'date_query' => array( 'after' => date('Ym-d', strtotime('-10 days')) ) ); $posts = get_posts($args); 
+24
source

The example from the document should work fine. get_posts () uses WP_Query () behind the scenes to make the actual request. For your case, the modified example should look something like this:

 // Create a new filtering function that will add our where clause to the query function filter_where( $where = '' ) { // posts in the last 30 days $where .= " AND post_date > '" . date('Ym-d', strtotime('-10 days')) . "'"; return $where; } add_filter( 'posts_where', 'filter_where' ); $query = get_posts(array ( 'numberposts' => 5, 'orderby'=>'comment_count', 'order'=>'DESC', 'post_type' => array ( 'post' ) )); remove_filter( 'posts_where', 'filter_where' ); 
+2
source

Source: https://habr.com/ru/post/946824/


All Articles