Function and usage of previous_post_link() in wordpress


Answers ( 1 )


    The previous_post_link() function in WordPress is a useful tool for navigating between posts. It displays a link to the previous post adjacent to the current one. This function is particularly handy in creating a more dynamic and interconnected blog or website experience. Below is a detailed explanation of its function and parameters:

    1. Function:

      • Purpose: Displays the previous post link that is adjacent to the current post.
    2. Description:

      • See also: get_previous_post_link() – This is a related function that retrieves the previous post link instead of displaying it.
    3. Parameters:

      • $format (string, optional): This parameter defines the link anchor format. It is how the link to the previous post will be presented. The default value is '« %link', which includes an HTML entity for the left-pointing double angle quotation mark followed by the link.
        • Default: '« %link'.
      • $link (string, optional): Specifies the permalink format of the link. By default, it uses '%title', which means the link will be displayed using the title of the previous post.
        • Default: '%title'.
      • $in_same_term (bool, optional): Determines whether the link should be to a post within the same taxonomy term. For instance, if you only want to show previous posts from the same category, you would set this to true.
        • Default: false.
      • $excluded_terms (int[] | string, optional): Allows specifying terms to be excluded. This can be an array or a comma-separated list of excluded term IDs. Posts within these terms will not be considered as the previous post.
        • Default: '' (empty string).
      • $taxonomy (string, optional): Specifies the taxonomy to be considered if $in_same_term is true. The default is 'category', but it could be any taxonomy, like 'post_tag' or a custom taxonomy.
        • Default: 'category'.

    Sample Usage:

    Here's an example of how to use previous_post_link() in a WordPress template:

    // Display link to the previous post in the same category, excluding posts in category with ID 10.
    previous_post_link('%link', 'Previous Post', true, '10', 'category'); 

    In this example, the function displays a link to the previous post that is in the same category as the current post ($in_same_term is true). It excludes any posts that belong to the category with an ID of 10 ($excluded_terms is '10'). The link is labeled 'Previous Post' ($link is 'Previous Post'), and the taxonomy considered is 'category' ($taxonomy is 'category').

Leave an answer