0

I'm after either a plugin suggestion or code suggestion that best handles images per post. Here's the scenario, every post could have up to 6 images, all to be assigned class names etc. All to be displayed on single.php. I'd like to be able to choose one of those 6 images that I'd like to display as a large image within the same template file.

Additionally, out of these 6 images I'd like to randomly call in 1 random one on to a custom page template in another loop elsewhere on the site.

To a novice like myself, this seems pretty complex and I wouldn't know where to start. How would I go about managing this? Is there a plugin that allows this functionality?

1 Answer 1

1

I'd like to be able to choose one of those 6 images that I'd like to display as a large image within the same template file.

This would probably fit as the Post Thumbnail/Post Featured Image.

Additionally, out of these 6 images I'd like to randomly call in 1 random one on to a custom page template in another loop elsewhere on the site.

Try using get_children() with the 'orderby' => 'rand' and 'numberposts' => 1 parameters.

Assuming you know how to get the ID of the post whose image attachments you want to display, as $post_id:

$random_post_images = get_children( array(
    'post_parent'    => $post_id,
    'post_mime_type' => 'image',
    'post_type'      => 'attachment'
    'orderby'        => 'rand',
    'numberposts'    => 1,
) );

This will return an array of one image, as an object:

$random_post_image_object = $random_post_images[0];

Now, you can output the image, using wp_get_attachment_image():

$random_post_image = wp_get_attachment_image( $random_post_image_object->ID, 'thumbnail' );
12
  • So, how do I add these 6 images to the post itself via the editing post page? Do I just click on the 'Upload media' button? Sorry, another question, how would I output all 6 images wrapped around a div on the single.php template?
    – egr103
    Commented May 25, 2012 at 17:01
  • You need to split separate questions into separate posts. One post: one question. :) Commented May 25, 2012 at 19:19
  • But in answer to your question: yes. You upload/attach images directly to the post, via the edit-post page. Commented May 25, 2012 at 19:19
  • But in order to fully understand the solution I need to ask more questions. Will this work for pages too? ;)
    – egr103
    Commented May 25, 2012 at 20:41
  • Yes, this will work for pages. Both blog posts and static pages support attachment post types. Commented May 25, 2012 at 20:51

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.