WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to add a check on the following piece of code that shows the arrows next/prev only if the next/prev image exists:

<div class="gallery-image"> 
    <p class="attachment">  
        <img src="<?php echo $att_image[0];?>" 
            width="<?php echo $att_image[1];?>" 
            height="<?php echo $att_image[2];?>"  
            alt="<?php $post->post_excerpt; ?>" />

        <span class="nav arrow previous">
            <?php previous_image_link(false); ?>

        <span class="nav arrow next">
            <?php next_image_link(false); ?>

This is an example of last image of a gallery so the next arrow shouldn't appears.

If you have any suggestions, please show me the right way to implement this behaviour :)

Thanks in advance,


share|improve this question
up vote 1 down vote accepted

The previous_image_link() only prints something if the there is a previous image. Similarly for next_image_link().

The problem is that you're styling the containing span element - which always exists. Instead you should style the a tag inside the span (which only appears when there is a next/previous image).

Alternatively, digging into the source, both previous_image_link and next_image_link call adjacent_image_link (see source). As noted above this prints the link only if the next/previous image exists. You can create your own function which, instead of printing the link - just returns true/false. However, it would still preferable to use the solution outlined above.

 * Similar to adjacent_image_link().
 * Returns true/false if the adjacent image exists.
 * @param $prev (bool) true - look for previous image, false -look for next.
function wpse57904_has_adjacent_image_link($prev = true) {
    global $post;
    $post = get_post($post);
    $attachments = array_values(get_children( array('post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') ));

    foreach ( $attachments as $k => $attachment )
        if ( $attachment->ID == $post->ID )

    $k = $prev ? $k - 1 : $k + 1;

    return isset($attachments[$k]);
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.