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.

I have a post in two categories, 1 and 2.

I want to get the previous post in the two categories, 1 and 2.

get_previous_post(true);

With that code I'm getting the previous post in category 1 or 2.

Any idea?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

get_previous_post uses get_adjacent_post() which has a bunch of filter hooks you can use but a much simpler approach would be to create your own function, something like this:

// Create a new filtering function that will add our where clause to the query
function date_filter_where( $where = '' ) {
    global $post;
    $where .= " AND post_date >= '".$post->post_date."'";
    return $where;
}

//then create your own get previous post function which will take an array of categories eg: 
// $cats = array('1','2');
function my_get_previous_post($cats){
    global $post;
    $temp = $post;
    $args = array(
        'posts_per_page' => 1,
        'post_type' => 'post',
        'post_status' => 'publish',
        'category__and' => $cats
    );
    add_filter( 'posts_where','date_filter_where' );
    $q = new WP_Query($args);
    remove_filter( 'posts_where','date_filter_where' );
    while ($q->have_posts()){
        $q->the_post;
        echo '<a href="'.get_permalink($post->ID).'">'.get_the_title($post->ID).'</a>';
    }
    $post = $temp;
    wp_reset_query();
}
share|improve this answer
    
Thanks for the response. I'm not getting the expected results with that code. It returned the same post instead of the above, and also the loop never ends. Here is the output for this code: $cats = array('6045','6241'); my_get_previous_post($cats); –  srcobranza Sep 13 '11 at 23:30
    
my bad i got the filter names wrong, updated my answer. –  Bainternet Sep 14 '11 at 0:26
    
I'm still getting the infinity loop, but it seems to work with query_posts instead of WP_Query. –  srcobranza Sep 14 '11 at 1:42
    
Makes no sense at all. –  Bainternet Sep 14 '11 at 6:05
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.