Function and usage of get_adjacent_post() in wordpress


Answers ( 1 )


    The get_adjacent_post() function in WordPress is a powerful tool for navigating between posts, often used for creating links to the next or previous posts on a blog or website. Here's a detailed explanation of this function and a sample usage:

    Function Signature

    get_adjacent_post( bool $in_same_term = false, int[]|string $excluded_terms = '', bool $previous = true, string $taxonomy = 'category' ): WP_Post|null|string

    Function Description

    get_adjacent_post() retrieves the adjacent post relative to the current post. This can be either the next or the previous post, depending on the parameters you provide.


    1. $in_same_term (bool, optional):

      • Determines whether the adjacent post should be in the same taxonomy term as the current post.
      • Default value is false, meaning it will not restrict the adjacent post to the same taxonomy term.
    2. $excluded_terms (int[]|string, optional):

      • Specifies the terms to be excluded when retrieving the adjacent post.
      • Can be an array or a comma-separated list of excluded term IDs.
      • Default value is an empty string '', indicating no terms are excluded.
    3. $previous (bool, optional):

      • Indicates whether to retrieve the previous post (true) or the next post (false).
      • Default value is true, so it retrieves the previous post by default.
    4. $taxonomy (string, optional):

      • Specifies the taxonomy to consider when $in_same_term is true.
      • Default value is 'category'.

    Return Values

    • WP_Post: Returns the post object if a corresponding post is found.
    • null: Returned if the global $post is not set.
    • Empty string (''): Returned if no corresponding adjacent post exists.

    Sample Usage

    Here's an example of how you might use get_adjacent_post():

    // Retrieve the previous post in the same category, excluding terms with IDs 10 and 15
    $previous_post = get_adjacent_post(true, '10,15', true, 'category');
    if ( is_a( $previous_post, 'WP_Post' ) ) {
        // Output the title of the previous post
        echo 'Previous Post: ' . get_the_title( $previous_post );
    } else {
        echo 'No previous post found.';

    In this example, get_adjacent_post() is configured to retrieve the previous post ($previous = true) in the same category ($taxonomy = 'category' and $in_same_term = true), excluding categories with term IDs 10 and 15 ($excluded_terms = '10,15'). The function then checks if a valid post is returned and outputs its title. If no post is found, it outputs a message indicating that no previous post is available.

Leave an answer