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

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


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

Any idea?


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()){
        echo '<a href="'.get_permalink($post->ID).'">'.get_the_title($post->ID).'</a>';
    $post = $temp;
| 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); – fsinisi90 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. – fsinisi90 Sep 14 '11 at 1:42
  • Makes no sense at all. – Bainternet Sep 14 '11 at 6:05

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.