Next and previous links category infinite loop

This is an extremely unreliable way to determine the next and previous category IDs:

$previouscat = $id - 1;
$nextcat = $id + 1;

There’s absolutely zero guarantee that the IDs of adjacent categories are only 1 apart. In fact the only time that would be the case is if all the categories were added at once, and no other tags or custom terms (like product categories) were ever added. Was the answer you got that from upvoted or accepted? I’d be concerned if it was.

Anyway, the fact is that Categories don’t really have an order. They’re just sorted by when they were inserted into the database and it doesn’t suit WordPress’ conception of Categories to imagine them having a fixed order.

That being said if you look at a list of categories they’ll be in a particular order and I guess in some cases you’ll want to get the adjacent categories for another category.

So the proper way to do that is to first get a list of all categories, then find the position of the current category in the resulting list. Then you can use +1 and -1 to get the next and previous categories based on position in the list because the position will always increment by one. Then you can use the categories in those positions for the links.

// Make sure the code only runs on category archives.
if ( is_category() ) {
    // Initialise variables to put the links into.
    $previous_link = '';
    $next_link = '';

    // Get an array of all category IDs.
    $category_ids = get_categories( ['fields' => 'ids'] );

    // Find the current category's position in the list of all categories.
    $position = array_search( get_queried_object_id(), $category_ids );

    // If there is a category in the list before the current category.
    if ( isset( $category_ids[$position-1] ) ) {
        // Set its link to the $previous_link variable.
        $previous_link =  get_category_link( $category_ids[$position-1] );
    }

    // If there is a category in the list after the current category.
    if ( isset( $category_ids[$position+1] ) ) {
        // Set its link to the $next_link variable.
        $next_link = get_category_link( $category_ids[$position+1] );
    }

    // Now you can output the links however you'd like.
    echo $previous_link;
    echo $next_link;
}