You’re looking for the get_adjacent_post function. This is a built-in wordpress function that you can use to get either the previous or next post from the current post.
To get the next post:
$next_post = get_adjacent_post( false, '', false, '' );
To get the previous post:
$prev_post = get_adjacent_post( false, '', true, '' );
You can also specify whether the post should be in the same taxonomy term and also set the taxonomy this is true.
get_adjacent_post( bool $in_same_term = false, array|string $excluded_terms="", bool $previous = true, string $taxonomy =
‘category’ )
Parameters
$in_same_term
(bool) (Optional) Whether post should be in a same taxonomy term.
Default value: false
$excluded_terms
(array|string) (Optional) Array or comma-separated list of excluded term IDs.
Default value: ”
$previous
(bool) (Optional) Whether to retrieve previous post. Default true
Default value: true
$taxonomy
(string) (Optional) Taxonomy, if $in_same_term is true.
Default value: ‘category’