WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Pull latest attachment from post? (49 posts)

  1. bcreighton
    Member
    Posted 6 years ago #

    Hi,

    Is there get attachment function that would allow me grab the latest attachment during the loop?

  2. Kafkaesqui

    Posted 6 years ago #

    You would first need to perform a quick query to figure out the latest attachment on a post:

    <?php
    global $wpdb;
    $attachment_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_parent = '$post->ID' AND post_status = 'inherit' AND post_type='attachment' ORDER BY post_date DESC LIMIT 1");
    ?>

    Here are some options from there on:

    Display link to attachment file (if an image, the image becomes the link):
    <?php the_attachment_link($attachment_id); ?>

    If an image, display the attachment:
    <?php echo get_attachment_icon($attachment_id); ?>

    Display the URL to the attachment's 'page':
    <?php echo get_attachment_link($attachment_id); ?>

  3. bcreighton
    Member
    Posted 6 years ago #

    Perfect! Thank you so much!

  4. choibellahotmailcom
    Member
    Posted 6 years ago #

    I'm trying to set up my wp template to call attachments and related data (jpg images and text) but can't find any sort of list of usable attachment-related tags other than these.

    I'd like to:

    1) Show the attachment data (the info I type in when I upload an image) on an archive page, but just for those in 1 category, not an entire list.

    2) Add rel="lightbox" to the image links so a lightbox plugin will work. I'm thinking I can add the rel portion to the actual code that runs when <?php the_attachment_link($attachment_id); ?> is called?

    Any help or suggestions will be much appreciated!

  5. n1cked
    Member
    Posted 6 years ago #

    This is a VERY helpfull topic.

    I want to do the same thing but instead of just the latest attachment, i want to pull ALL attachments for a post.

    How do i turn this query into something that generates an array of all the files.

    $attachment_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_parent = '$post->ID' AND post_status = 'inherit' AND post_type='attachment' ORDER BY post_date DESC LIMIT 1");

  6. Sam_a
    Member
    Posted 6 years ago #

    > I want to do the same thing but instead of just the latest attachment, i want to pull ALL attachments for a post.

    You can do this with WordPress's get_posts function; see, e.g., http://codex.wordpress.org/Template_Tags/get_posts#Show_attachments_for_the_current_post

    You can use some of the functions Kafkaesqui mentioned above (these are mostly undocumented: http://codex.wordpress.org/Category:Attachments).

  7. harshd
    Member
    Posted 6 years ago #

    Excellent topic and thanks for the reply Kafkaesqui.

  8. Thad Allender
    Member
    Posted 6 years ago #

    Good thread. Lets keep it going. We could all do some really fun stuff with our photo galleries (jquery stuff) if we could spit them out into an unordered list on single.php.

    On single.php, I would like the flexibility to do the following:

    <ul>
    <li><a href="#medium-image"><img src="#thumbnail" /></a></li>
    <li><a href="#medium-image-2"><img src="#thumbnail-2" /></a></li>
    <li><a href="#medium-image-3"><img src="#thumbnail-3" /></a></li>
    </ul>

    What code might one use on single.php to achieve the desired output? I've attempted the suggestions mentioned on this thread posted here:
    http://codex.wordpress.org/Template_Tags/get_posts#Show_attachments_for_the_current_post

    but for whatever reason, when posted inside the loop on single.php it runs the loop for all posts that contain galleries.

    Ideally, single.php would contain conditional logic that would only display the container divs and class for the gallery if a gallery exists.

  9. Sam_a
    Member
    Posted 6 years ago #

    <?php if ( $images = get_children(array(
    		'post_parent' => get_the_ID(),
    		'post_type' => 'attachment',
    		'post_mime_type' => 'image',
    	))) : ?>
    	<ul>
    		<?php foreach( $images as $image ) :  ?>
    			<li><?php echo wp_get_attachment_link($image->ID, 'medium'); ?></li>
    		<?php endforeach; ?>
    	</ul>
    <?php else: // No images ?>
    	<!-- This post has no attached images -->
    <?php endif; ?>
  10. mores
    Member
    Posted 6 years ago #

    Sam_a ... amazing, thank you.
    I was actually looking for a combo of all this. Just the newest attachment, but not in full and not in thumbnail, but the medium sized thingie.
    I created a functions.php file in my theme directory.

    function postimage($size=medium) {
    	if ( $images = get_children(array(
    		'post_parent' => get_the_ID(),
    		'post_type' => 'attachment',
    		'numberposts' => 1,
    		'post_mime_type' => 'image',)))
    	{
    		foreach( $images as $image ) {
    			echo wp_get_attachment_link($image->ID, $size);
    		}
    	} else {
    		echo "No Image";
    	}
    }

    But now I want to get more control over this and specifically either remove the link to the full-size image OR make it lightbox-compatible. Any way to get just the medium-sized preview pic url? Or add the necessary "rel=..." part to the img link?

  11. Sam_a
    Member
    Posted 6 years ago #

    Something like

    <a href="<?php echo wp_get_attachment_url($image->ID); ?>" rel="lightbox"><?php echo wp_get_attachment_image( $image->ID, 'medium' ); ?></a>

  12. mores
    Member
    Posted 6 years ago #

    Awesome, thank you so much.
    Here's what my code looks like now:

    function postimage($size=medium) {
    	if ( $images = get_children(array(
    		'post_parent' => get_the_ID(),
    		'post_type' => 'attachment',
    		'numberposts' => 1,
    		'post_mime_type' => 'image',)))
    	{
    		foreach( $images as $image ) {
    			$attachmenturl=wp_get_attachment_url($image->ID);
    			$attachmentimage=wp_get_attachment_image( $image->ID, $size );
    
    			echo '<a href="'.$attachmenturl.'" rel="lightbox">'.$attachmentimage.'</a>';
    		}
    	} else {
    		echo "No Image";
    	}
    }

    I can call it in my template simply by using

    <?php postimage(); ?>
    or
    <?php postimage('thumbnail'); ?>

  13. omgitztrey
    Member
    Posted 6 years ago #

    Excellent thread! The question I have is how can I get it to pull random thumbnails from any post? Any maybe include the title of the post?

    I was using a different code before the 2.5 upgrade and now it won't work.

    <?php
    global $wpdb;
    $numposts = 4;
    
    $rand_posts = $wpdb->get_results("SELECT * FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    WHERE post_status = 'publish'
    AND wposts.ID = wpostmeta.post_id
    AND wpostmeta.meta_key = 'thumb'
    ORDER BY RAND() LIMIT $numposts");
    foreach($rand_posts as $post) :
    setup_postdata($post);
    ?>

    I sort of want it like People's Magazine "What's Hot" section
    http://offtherack.people.com/

  14. arminbw
    Member
    Posted 6 years ago #

    Just to send out a warning: If the EXIF data of an image contains special characters, certain functions in WordPress 2.5.1 will only return the URL of the full size image.
    See: ticket 7278

  15. Sam_a
    Member
    Posted 5 years ago #

    The question I have is how can I get it to pull random thumbnails from any post?

    Something like

    $images = get_children('post_type=attachment&post_mime_type=image&post_parent=0');
    
    $image = $images[array_rand($images)];
    
    $parent =& get_post($image->post_parent);
    
    echo '<a href="'
    	. get_permalink($image->post_parent)
    	. '">'
    	. wp_get_attachment_image( $image->ID, 'thumbnail' )
    	. apply_filters( 'the_title', $parent->post_title )
    	. '</a>';
  16. 007casper
    Member
    Posted 5 years ago #

    Awesome thread!

    I list ten other articles at the end of a post, where I would like to show an icon image next to the title.

    However, all the codes I tried here brings up an image for the first title, and not for the rest. Also, images link to image url, not to post url that is attached. Strange enough, the rest of the nine titles stated missing attachment, even though I have images for those posts.

    I have tried
    <?php the_attachment_link( 13, false, array(48, 48) );?>
    I got it from here

    http://codex.wordpress.org/Template_Tags/the_attachment_link

    it works but "13" shows the specific category, and not the actual listed title post.

    Please, help. Thank you in advance.
    007casper

  17. 007casper
    Member
    Posted 5 years ago #

    *bump ~ help

  18. Sam_a
    Member
    Posted 5 years ago #

    I list ten other articles at the end of a post, where I would like to show an icon image next to the title.

    What code are you using to list the 10 articles?

  19. 007casper
    Member
    Posted 5 years ago #

    <?php query_posts('showposts=10&offset=3'); ?> <!-- 10 most recent posts -->
    				<ul>
    				<h2>Other Articles</h2>
    					<?php while (have_posts()) : the_post(); ?>
    					<li><span class="title"><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></span> | <span class="comment"><a href="<?php the_permalink() ?>#commenting" title="Jump to the comments"><?php comments_number('0 Comments','1 Comment','% Comments'); ?></a></span>| <span class="meta"> - <?php the_time('l, F j, Y G:i'); ?></span></li>
    					<?php endwhile; ?>
    				</ul>
  20. Matt Hill
    Member
    Posted 5 years ago #

    I needed a good pointer on how to display image attachments for posts from a particular category, and am very thankful for the function posted by 'mores' above. I made some minor change so that I can query just the category I want and also to remove the link on each image as this is just a slideshow of the full size images:

    function categoryImages($size=large,$catID) {
    	$posts=query_posts('cat='.$catID);
    	foreach( $posts as $post ) {
    		if ( $images = get_children(array(
    			'post_parent' => $post->ID,
    			'post_type' => 'attachment',
    			'numberposts' => -1,
    			'post_mime_type' => 'image',)))
    		{
    			foreach( $images as $image ) {
    				$attachmenturl=wp_get_attachment_url($image->ID);
    				$attachmentimage=wp_get_attachment_image( $image->ID, $size );
    				echo $attachmentimage;
    			}
    		} else {
    			echo "No Images";
    		}
    	}
    }

    The function to place in your theme template is:

    <?php categoryImages('large',22); ?>

    ...or whatever your category number is.

  21. Sam_a
    Member
    Posted 5 years ago #

    I list ten other articles at the end of a post, where I would like to show an icon image next to the title

    Try something like this (there are a lot of "post image" functions):

    <?php the_post_image(); ?>

    function the_post_image($size = 'thumbnail') {
    	$id = get_the_ID();
    	if ( empty($id) ) {
    		trigger_error( __FUNCTION__ . "(): Couldn't get current post ID", E_USER_WARNING);
    		return false;
    	}
    	$images = get_children(array(
    		'numberposts' => 1,
    		'post_parent' => $id,
    		'post_type' => 'attachment',
    		'post_mime_type' => 'image',
    	));
    	if ( empty($images) ) {
    		// Post has no attached images
    		return false;
    	}
    	$image = array_pop($images);
    	$output = wp_get_attachment_image($image->ID, $size);
    	if ( empty($output) ) {
    		trigger_error( __FUNCTION__ . "(): Couldn't print image for attachment #{$image->ID}", E_USER_WARNING);
    		return false;
    	}
    	echo $output;
    }
  22. Sam_a
    Member
    Posted 5 years ago #

    You can use it inside the hyperlink in the "Other Articles" loop:

    … <a href="<?php the_permalink() ?>"><?php the_post_image(); ?> <?php the_title(); ?></a> …

    Put the post_image() function definition in your template or in your theme's functions.php file.

  23. 007casper
    Member
    Posted 5 years ago #

    Thank you so much Sam_a! I really appreciate it. I got the link and the image working for the first article, unfortunately it doesn't display images for the rest of the remaining nine posts in the list.

    I wonder what I am doing wrong...

  24. 007casper
    Member
    Posted 5 years ago #

    Here is the full code in a nutshell... does anyone have any idea why images dont show up for the rest of the titles in the list.

    <?php get_header(); ?>
     				 <div id="featured">
    					<?php query_posts('showposts=3'); ?>
    					<?php while (have_posts()) : the_post(); ?>
    					<h2><?php the_category(', '); ?><i> - <?php the_time('l, F j, Y G:i'); ?> - <a href="<?php the_permalink() ?>#commenting" title="Jump to the comments"><?php comments_number('0 Comments','1 Comment','% Comments'); ?></a></i></h2>
    					<h1><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
    					<?php the_content('Continue...'); ?>
    					<?php endwhile; ?>
    					<div class="clear"></div>
    				</div> <!-- END -->
    				<?php query_posts('showposts=10&offset=3'); ?> <!-- 10 most recent posts -->
    				<ul>
    				<h2>Other Articles</h2>
    					<?php while (have_posts()) : the_post(); ?>
    					<li><a href="<?php the_permalink() ?>"><?php the_post_image(); ?></a><span class="title"><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></span> | <span class="comment"><a href="<?php the_permalink() ?>#commenting" title="Jump to the comments"><?php comments_number('0 Comments','1 Comment','% Comments'); ?></a></span><span class="meta"> - <?php the_time('l, F j, Y G:i'); ?></span></li>
    					<?php endwhile; ?>
    				</ul>
    
    				<p class="link"><a href="<?php echo get_option('home'); ?>/archives" title="View Archives">archives</a>
    </div>
    			 <div class="column_mainbottom">.</div>
    			</div> <!-- END -->
    			<?php get_sidebar(); ?> <!-- Calling the sidebar with the AJAX box, or the widgets -->
    		</div>
    <?php get_footer(); ?>
  25. mores
    Member
    Posted 5 years ago #

    @gambit37 ... you saved my day.
    I managed to create a combined version of my code and your category-sensitive modification (because I think I need variable number of images).

    This saved my project. I got all kinds of images on the front page, logos and buttons etc. that really threatened to make me look bad in the eyes of my customer :)

    Do you have a website with a "donate" button?

  26. Matt Hill
    Member
    Posted 5 years ago #

    I have a website, but no donate button. :-) Not to worry, I'm glad to help.

  27. mores
    Member
    Posted 5 years ago #

    well thank you very much for helping. Great community, this is!

    I noticed, this way of going through the posts of a category will give me X number of images randomly TIMES Y NUMBER OF POSTS in that category.

    Is there a way to sort of turn the whole thing upside down and have it go through the posts randomly, select one random image, until the desired number of images has been displayed?
    This is not life-threatening, since I can manage to fake the whole thing by knowing the number of posts and using a div with "overwrite:none" to hide the excess pics. But it would be interesting to learn, maybe for a next project, or someone else in this community.

  28. omgitztrey
    Member
    Posted 5 years ago #

    I got the code to work on the index.php and single.php... great stuff.

    Is there anyway to make it work in attachment.php/image.php? Thanks

  29. omgitztrey
    Member
    Posted 5 years ago #

    function postimage($size=medium) {
    	if ( $images = get_children(array(
    		'post_parent' => get_the_ID(),
    		'post_type' => 'attachment',
    		'numberposts' => 1,
    		'post_mime_type' => 'image',)))
    	{
    		foreach( $images as $image ) {
    			$attachmenturl=wp_get_attachment_url($image->ID);
    			$attachmentimage=wp_get_attachment_image( $image->ID, $size );
    
    			echo '<a href="'.$attachmenturl.'" rel="lightbox">'.$attachmentimage.'</a>';
    		}
    	} else {
    		echo "No Image";
    	}
    }

    Using the above code by Mores... is it possible to make it "count" before executing the echo?

    I want it to pull images relevant to the post to display on the index as thumbnails, but only if there are x number of images available.

  30. 3stripe
    Member
    Posted 5 years ago #

    Thanks for the pointers on this thread, really helpful!

    I am trying to display a link to the first attached mp3 on a post, but so that it says simply 'Download', not the actual title/filename of the mp3...

    But none of the above allow this as far as I can tell?

    I could change the name of every mp3 to 'Download' but that seems a hack too far! :)

Topic Closed

This topic has been closed to new replies.

About this Topic