WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Need Help with random image display (2 posts)

  1. krembo99
    Member
    Posted 5 years ago #

    Hi all, this time it is ME who needs some help :-)
    I need to have a random image function, that takes images from ALL attachemnts, all posts, and displays a random image .
    I have searched all the posts here, but none really helped, and the codes inside , all derivants or similar to :

    function randomimage_mores($size=medium,$num=1,$cat=0) {
    	$posts=query_posts('cat='.$cat);
    	foreach( $posts as $post ) {
    		if ( $images = get_children(array(
    			'post_parent' => $post->ID,
    			'post_type' => 'attachment',
    			'numberposts' => $num,
    			'orderby' => 'rand()',
    			'post_mime_type' => 'image',)))
    		{
    			$zeiger = 1;
    
    			foreach( $images as $image ) {
    				if ($zeiger != $num) {
    					$zwischen="    ";
    				} else {
    					$zwischen = "";
    					$zeiger = 1;
    				}
    				$attachmenturl=wp_get_attachment_url($image->ID);
    				$attachmentimage=wp_get_attachment_image( $image->ID, $size );
    				echo '<a href="'.$attachmenturl.'" rel="lightbox">'.$attachmentimage.'</a>'.$zwischen;
    				$zeiger++;
    			}
    		} else {
    			echo "No Image";
    		}
    	}
    }

    that are using wp_get_attachment_image , , for some reason did not work for me . (display ALL images)
    I have categories, and sub-categories, and need only 1 (ONEā‚¬) photo to be desplayed, on full page......
    I also tried to just take a custom query , and use wp_get_attachment_image, but to no avail..

    any help would be appreciated.

  2. krembo99
    Member
    Posted 5 years ago #

    Ok, for those of you who might need it : I have resolved the issue with a custom query like so :

    $querystr = "
    					SELECT wposts.ID, wposts.post_title
    					FROM $wpdb->posts wposts
    					WHERE wposts.post_type = 'attachment'
    					AND wposts.post_mime_type = 'image/jpeg'
    					ORDER BY RAND() LIMIT 1
    				";
    
    				$id = $wpdb->get_results($querystr, ARRAY_A);
    
    				$title = wp_get_attachment_image($id[0]['post_title']);
    				$url =  wp_get_attachment_url($id[0]['ID']);
    				if(empty($url))
    				{
    					$url = get_bloginfo('template_url').'/default.jpg';
    				}
    			?>
    			<img src="<?php echo $url ?>" alt="<?php echo $title ?>" class="random" />

Topic Closed

This topic has been closed to new replies.

About this Topic