I’m trying to get a random image from a page (not a post), however, it keeps giving me the same page each time to pull the image from.
$current_id = get_the_ID();//id for page/post we are on
echo 'current_id=' . $current_id . '<hr>';//DEBUG
$args = array('post_type' => 'page', 'numberposts' => 1, 'orderby' => 'rand', 'exclude' => $current_id, 'post_parent' => 11);//only pull pages under id-11 "ARTWORK" since it is where we put all the pages with images we would need
$rand_posts = get_posts($args);
var_dump($rand_posts);//gets same page each time! its not random :(
foreach($rand_posts as $post)
{
$parent = get_the_ID();
echo 'parent=' . $parent . '<hr>';//DEBUG
$args = array('post_type' => 'attachment', 'numberposts' => 1, 'orderby' => 'rand', 'post_parent' => $parent);
$attachments = get_posts($args);
if ($attachments)
{
echo '<div class="sidebar">';
foreach ($attachments as $attachment)
{
setup_postdata($attachment);
//the_attachment_link($attachment->ID, false);
echo '<a href="' . get_permalink($parent) . '">';
echo wp_get_attachment_image($attachment->ID, 'sidebar');
echo get_the_title($parent);
echo '</a>';
}
echo '</div><!--.sidebar-->';
}
else
{
//need backup content
}
}//end foreach