Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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)
share|improve this question
1  
what happens in the case where the current post is one of the 5 latest posts? –  Milo Nov 12 '12 at 4:10
add comment

1 Answer

up vote 1 down vote accepted
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' );

}
share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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