0

How can i display 5 posts from current category (exclude current post). Order by post time.

Example:

  • To day news to reading 3 (12/11/2012 - 8:10 PM)
  • To day news to reading 2 (12/11/2012 - 6:07 AM)
  • To day news to reading 1 (12/11/2012 - 6:05 AM)
  • Yesterday news to reading 2 (11/11/2012 - 9:10 PM)
  • Yesterday news to reading 1 (11/11/2012 - 7:12 AM)
  • 1
    what happens in the case where the current post is one of the 5 latest posts? – Milo Nov 12 '12 at 4:10
1
function filter_where_older( $where = '' ) {
    $date = get_the_time('Y-m-d H:i:s');
    $where .= " AND post_date < '$date'";
    return $where;
}

function filter_where_newer( $where = '' ) {
    $date = get_the_time('Y-m-d H:i:s');
    $where .= " AND post_date > '$date'";
    return $where;
}

$category = get_the_category();
if(!empty($category)) {

    $cat_id = $category[0]->term_id;

    add_filter( 'posts_where', 'filter_where_older' );
    // retrieve older posts from current post
    $query = new WP_Query( "cat=$cat_id&order=ASC&posts_per_page=5" );
    remove_filter( 'posts_where', 'filter_where_older' );

    add_filter( 'posts_where', 'filter_where_newer' );
    // retrieve newer posts from current post
    $query = new WP_Query( "cat=$cat_id&posts_per_page=5" );
    remove_filter( 'posts_where', 'filter_where_newer' );

}
  • Thanks @Mridul Aggarwal! Older list is ok. but newer list is sorting upside down. – Bits Hcm Nov 13 '12 at 5:58
  • That was intentional, try adding &order=ASC in the parameter of WP_Query. In the answer, i added this only in one of them – Mridul Aggarwal Nov 13 '12 at 9:11
  • filter_where_newer: $where .= " AND post_date > '$date'"; So the query will get all posts which have post_date > current post date. If we use &order=ASC it will display 5 newest posts of current category. when i change &order=DESC newer list is sorting upside down. :) Sorry if my english is not good :D Thanks for help @Mridul Aggarwal! – Bits Hcm Nov 14 '12 at 3:10
  • $query->posts=array_reverse($query->posts); should reverse the order. Try it after the newer query. Also call $query->rewind_posts() to reset the state – Mridul Aggarwal Nov 14 '12 at 9:51

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.