0

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];?>"  
            class="attachment-medium" 
            alt="<?php $post->post_excerpt; ?>" />

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

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

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,

Fabio

1 Answer 1

1

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 )
            break;

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

    return isset($attachments[$k]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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