Function and usage of get_adjacent_image_link() in wordpress


Answers ( 1 )


    The get_adjacent_image_link() function in WordPress is used to retrieve the markup for the link to the next or previous image attachment within the same post. This function is particularly useful when creating image galleries or navigating between images attached to a post.

    Function Signature

    get_adjacent_image_link( bool $prev = true, string|int[] $size = 'thumbnail', bool $text = false ): string


    • Function Purpose: Gets the markup for the link to the next or previous image attachment that shares the same post parent as the current image.
    • How It Works: It retrieves the current attachment object from the global $post variable in WordPress.


    1. $prev (bool, optional): Determines whether to fetch the link for the previous (true) or next (false) image attachment. The default value is true.

      • Default: true
    2. $size (string|int[], optional): Specifies the size of the image for the link. It can be any registered image size name in WordPress, or an array of width and height values in pixels.

      • Example of a size name: 'medium', 'large'
      • Example of size array: [200, 300] (200 pixels wide, 300 pixels tall)
      • Default: 'thumbnail'
    3. $text (bool, optional): If set to true, the link text will be displayed. Otherwise, only the image will be linked.

      • Default: false

    Return Value

    • Type: string
    • Description: Returns the HTML markup for the image link. This could be a simple <a> tag wrapping an <img> tag, or it could include additional text if $text is set to true.

    Sample Usage

    // To get the previous thumbnail-sized image link without link text
    echo get_adjacent_image_link(true, 'thumbnail', false);
    // To get the next medium-sized image link with link text
    echo get_adjacent_image_link(false, 'medium', true);
    // To get the previous image link with custom size [200, 300] and without link text
    echo get_adjacent_image_link(true, [200, 300], false);

    Practical Use-Cases

    • Image Navigation in Galleries: Useful in image gallery templates where visitors can navigate through images attached to a post.
    • Attachment Pages: On attachment pages, it provides a way to browse through other images attached to the same post.

    Additional Notes

    • This function is part of the WordPress Attachment Functions and relies on the global post context.
    • It's important to ensure that the specified image size exists or is registered in WordPress. Unrecognized sizes will result in default behavior.
    • This function is typically used within the Loop or in templates where the global $post variable represents an attachment object.

Leave an answer