excluded_categories parameter in next_post_link() behaving unexpectedly

It makes perfect sense, but kind of backwards. I think the query that is executed to “exclude” posts from categories is grabbing all of the categories (this may return category IDs 1, 2, 5, 7, 11, 13, 15, 16, and 23) initially then checking the “exclude_category” param (“11 and 13 and 15”) and running the query to grab all posts that BELONG in categories 1, 2, 5, 7, 16, and 23 (skipping over 11, 13, and 23). So technically the returned result is indeed correct.

So you can write a function similar to what i’ve pasted below:

function prev_next_dont_include( $ids ) {
foreach ( get_categories() as $category ) : // loop thru all WP cats
    if ( !in_array( $category->cat_ID, $ids ) ) : // check if cat id is in $ids
        $categories[] = $category->cat_ID; // build list of real excluded ids
    endif;
endforeach; 
return implode( ' and ', $categories ); // "1 and 2 and 5 and 7 and 16 and 23"
}

Now you can use that like this:

previous_post_link('%link',  __( '<span class="meta-nav">&larr;</span> Previous Article', 'twentyeleven' ), false, prev_next_dont_include( array( 11, 12, 15 ) ) );

Hopefully this will help someone out as it sure saved me.

Leave a Comment