Skip to content

Instantly share code, notes, and snippets.

@eteubert
Created November 25, 2011 10:04
Show Gist options
  • Select an option

  • Save eteubert/1393186 to your computer and use it in GitHub Desktop.

Select an option

Save eteubert/1393186 to your computer and use it in GitHub Desktop.
WordPress: Link Attachments to the Post Displaying Them
<?php
if ( $attachment->post_parent > 0 ) {
$link = get_permalink( $attachment->post_parent );
} else {
$link = get_attachment_link( $attachment->ID );
}
$img = wp_get_attachment_image( $attachment->ID );
?>
<a href="<?php echo $link ?>"><?php echo $img ?></a>
<?php
$args = array(
'posts_per_page' => 5,
'post_type' => 'attachment'
);
$attachments = new WP_Query( $args );
if ( $attachments->have_posts() && $attachments->post_count >= 3 ) : ?>
<div class="gallery">
<div class="items">
<?php foreach ( $attachments->posts as $attachment ):
if ( $attachment->post_parent > 0 ) {
$link = get_permalink( $attachment->post_parent );
} else {
$link = get_attachment_link( $attachment->ID );
}
$img = wp_get_attachment_image( $attachment->ID, 'gallery' );
?>
<a href="<?php echo $link; ?>"><?php echo $img; ?></a>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
<?php wp_reset_query(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment