Advertisement
chrishajer

Shortcode to link image to single post

Nov 17th, 2012
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.62 KB | None | 0 0
  1. <?php
  2. // http://www.gravityhelp.com/forums/topic/link-uploaded-image-to-created-post#post-76548
  3. // http://wordpress.stackexchange.com/a/44069
  4. // Chris Hajer 17 November 2012
  5. add_shortcode('gf_postimage', 'get_image_with_link');
  6. function get_image_with_link() {
  7.         global $post;
  8.         $all_images = get_posts( array(
  9.                 // Return just the first attachment
  10.                 'numberposts' => 1,
  11.                 'order'=> 'ASC',
  12.                 'post_parent' => $post->ID,
  13.                 'post_mime_type' => 'image',
  14.                 'post_type' => 'attachment'
  15.         ) );
  16.         // Step through all image attachments
  17.         foreach ( $all_images as $image ) {
  18.                 // Get the attachment ID
  19.                 $image_id = $image->ID;
  20.                 // Get the image alt tag
  21.                 $image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
  22.                 // Get the attachment URL for the large size
  23.                 $image_info = wp_get_attachment_image_src( $image_id, 'large' );
  24.                 // Get the parent post ID
  25.                 $parent_id = $image->post_parent;
  26.                 // Get the parent post Title
  27.                 $parent_title = get_the_title( $parent_id );
  28.                 // Get the parent post permalink
  29.                 $parent_permalink = get_permalink( $parent_id );
  30.         }
  31.         $post_content_prepend = "<a href='$parent_permalink' title='$parent_title'><img src='{$image_info[0]}' width='{$image_info[1]}' height='{$image_info[2]}' alt='$image_alt' class='size-large alignnone wp-image-$image_id'  /></a>";
  32.         return $post_content_prepend;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement