Last Updated: February 25, 2016
·
1.493K
· dscotts3

excluded_categories parameter in next_post_link() behaving unexpectedly

I've ran a couple of scenarios where I need to exclude categories when using the nextpostlink() function. This doesn't behave as I expected when a post belongs to multiple categories and one of the categories the post belongs to is not excluded, the post still shows up. So, I came up with this handy function to be added in your theme's functions.php file:

function prev_next_dont_include( $ids ) {
    foreach ( get_categories() as $category ) : 
        if ( !in_array( $category->cat_ID, $ids ) ) : 
            $categories[] = $category->cat_ID; 
        endif;
    endforeach; 
    return implode( ' and ', $categories ); 
}

Then you can call this in your view like this:

previous_post_link( 'Previous Article', false, prev_next_dont_include( array( 11, 12, 15 ) );