我知道如何添加图像和图库。每次加载页面时,我需要在页面上随机显示一张厨房展示的图像。
页面一次只能显示一个图像。
是否有插件或短代码来执行此操作?我知道如何使画廊的随机,但他们显示所有的图像。
Answer:
$args = array(
\'post_type\' => \'attachment\',
\'numberposts\' => 1,
\'orderby\' => \'rand\',
\'post_status\' => null,
\'post_parent\' => get_the_ID(),
\'post_mime_type\' => \'image\'
);
have_posts(); //must be in the loop
the_post(); //set the ID
$images = get_children( $args );
if ($images) {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, \'full\' );
}
}
wp_reset_query();
SO网友:Alexandre Babeanu
此代码回答了问题。在包含图库的页面或帖子中,它将从图库中随机抽取一幅图像,并仅显示该图像。它进入wordpress循环(这里的代码实际上包括循环)。
<?php //start the loop ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php // get the post\'s gallery ?>
<?php if ( get_post_gallery() ) : $gallery = get_post_gallery( get_the_ID(), false ); ?>
<?php //get gallery picture ids string seperates the ids and puts them in an array. ?>
<?php $pic_ids = explode(",", $gallery[\'ids\']);?>
<?php // set a random int < to the size of the array containing ids.?>
<?php $i=rand(0, count($pic_ids)-1);?>
<?php //get image corresponding to the random id?>
<?php echo wp_get_attachment_image( $pic_ids[$i],\'full\', false, \'\' ); ?>
<?php endif; ?>
<?php endwhile; else : ?>
<p><?php _e( \'Sorry, no page found.\' ); ?></p>
<?php endif; ?>