这可以通过相当简单的元素来解决:一个短代码和文本小部件。
首先,我们为小部件启用短代码功能:
// Enable shortcodes in the Text Widget
add_filter( \'widget_text\', \'do_shortcode\' );
有用:
Shortcodes everywhere然后,我们创建一个短代码,从给定的帖子或页面抓取图像,并显示随机数。由于我们将以随机顺序加载,因此在每个页面加载时,图像都会有所不同。
用法将为[random-image id="99" total="4"]
. “id”是帖子/页面id。您甚至可以将此帖子留在Draft
状态,因此它不会显示在站点中。“total”是可选的,表示要显示的图像数,如果附加的图像较少,则无所谓,它将显示所有存在的图像。
您可以有几个帖子来存储图像,并为每个帖子使用一个小部件。可以创建自定义帖子类型get_posts
部分内容变得复杂了,但我将把它作为练习留给读者;)
查看评论以了解更多详细信息:
// Declare our shortcode
add_shortcode( \'random-image\', \'wpse_45638_random_image\' );
/**
* Shortcode
*/
function wpse_45638_random_image( $atts, $content = null )
{
// ID not provided, bail out
if( !isset( $atts[\'id\'] ) )
return;
// Initiate variables,
$html = \'\';
$total = isset( $atts[\'total\'] ) ? $atts[\'total\'] : -1;
$gallery = wpse_45638_get_gallery( $atts[\'id\'], $total );
// No images, bail out
if( !$gallery )
return;
// Build the thumbnails
foreach( $gallery as $image )
{
$html .= \'<div style="padding:10px;width:75px;float:left"><a href="\'
. $image[\'file\']
. \'"><img src="\'
. $image[\'t_file\']
. \'" style="width:100%"></a></div> \';
}
// Return contents of the shortcode
return $html;
}
/**
* Get images from a post
*
* @param int $post_id Target post/page/cpt
* @param int $total Number of images to retrieve
*/
function wpse_45638_get_gallery( $post_id, $total )
{
$args = array(
\'post_type\' => \'attachment\',
\'numberposts\' => $total,
\'post_parent\' => $post_id,
\'post_mime_type\' => \'image\',
\'orderby\' => \'rand\'
);
$attachments = get_posts( $args );
$arr = array();
if ($attachments)
{
foreach ( $attachments as $img )
{
// Grab our data - This can be improved
$data = wp_get_attachment_metadata( $img->ID );
$thumb = wp_get_attachment_thumb_url( $img->ID);loga($thumb);
$file = wp_get_attachment_url( $img->ID);loga($file);
$arr[] = array(
\'width\' => $data[\'width\'],
\'height\' => $data[\'height\'],
\'file\' => $file,
\'t_width\' => $data[\'sizes\'][\'thumbnail\'][\'width\'],
\'t_height\' => $data[\'sizes\'][\'thumbnail\'][\'height\'],
\'t_file\' => $thumb,
);
}
return $arr;
}
return false; // no images found
}