WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Random post Image (2 posts)

  1. pixeljam
    Member
    Posted 3 years ago #

    Hi guys!
    I'm trying to modify the Autofocus template, actually I quite stripped it down a bit =)
    I would like to modify the home page retrieving a random image from each post instead of the last one.

    function random_image_url($size=large) {
    
    	global $post;
    	if ( $images = get_children(array(
    		'post_parent' => get_the_ID(),
    		'post_type' => 'attachment',
    		'numberposts' => 1,
    		'orderby' => 'rand()',
    		'post_mime_type' => 'image',)))
    	{
    		foreach( $images as $image ) {
    			$attachmenturl=wp_get_attachment_image_src($image->ID, $size);
    			$attachmenturl=$attachmenturl[0];
    			echo ''.$attachmenturl.'';
    		}
    
    	}  else {
    		echo '' . get_bloginfo ( 'stylesheet_directory' ) . '/img/no-attachment.gif';
    	}
    }

    that is the stripped down version of post_image_url with a different name (in case I mess it up :P).
    I tried to add orderby=rand but to the get_children function, but doesn't work, any idea?
    Cheers!

  2. pixeljam
    Member
    Posted 3 years ago #

    Ok solved, I just missed the option to switch get_children with get_posts!! what a dumb!
    Here is the working code if anybody needs a random image ;)
    
    function random_image_url($size=large) {
    
    	global $post;
    	if ( $images = get_posts(array(
    		'post_parent' => get_the_ID(),
    		'post_type' => 'attachment',
    		'numberposts' => 1,
    		'orderby' => 'rand',
    		'post_mime_type' => 'image',)))
    	{
    		foreach( $images as $image ) {
    			$attachmenturl=wp_get_attachment_image_src($image->ID, $size);
    			$attachmenturl=$attachmenturl[0];
    			echo ''.$attachmenturl.'';
    		}
    
    	}  else {
    		echo '' . get_bloginfo ( 'stylesheet_directory' ) . '/img/no-attachment.gif';
    	}
    }

Topic Closed

This topic has been closed to new replies.

About this Topic