html随机显示图片,DUX主题实现缩略图随机显示

高海鹏老师的博客目前使用某网友分享出来的DUX主题,这个主题看起来很不错,但是缩略图的设置很简单:如果设置了“特色图像”,就以“特色图像”作为缩略图;如果没有设置“特色图像”,则显示一幅默认的图片。经过研究,我最终实现了DUX主题随机缩略图的显示:如果设置了“特色图像”,就以“特色图像”作为缩略图;如果没有设置“特色图像”,则自动调取文章内第一幅图片作为缩略图;如果文章内没有图片,则随机显示一幅图片。

具体实现方法如下(以DUX 1.3版本为例):

首先修改inc/fn.php,打开fn.php文件,找到第463行,将以下内容:

$html = sprintf('', get_stylesheet_directory_uri() . '/img/thumbnail.png', $class);

修改为:

$random = mt_rand(1, 20);

$html = sprintf('', get_stylesheet_directory_uri() . '/img/random/'.$random.'.jpg', $class);

接下来,我们在主题的img下建立一个文件夹random,复制进20张图片,并重命名为1.jpg、2.jpg……20.jpg,这样,DUX主题就实现了自动显示随机缩略图的功能,如果文章没有设置“特色图像”,将随机显示一幅图片。

下面我来实现自动调取第一幅图片,在主题的functions.php文件中加入如下代码:

function autoset_featured() {

global $post;

$already_has_thumb = has_post_thumbnail($post->ID);

if (!$already_has_thumb) {

$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );

if ($attached_image) {

foreach ($attached_image as $attachment_id => $attachment) {

set_post_thumbnail($post->ID, $attachment_id);

}

}

}

} //end function

add_action('the_post', 'autoset_featured');

add_action('save_post', 'autoset_featured');

add_action('draft_to_publish', 'autoset_featured');

add_action('new_to_publish', 'autoset_featured');

add_action('pending_to_publish', 'autoset_featured');

add_action('future_to_publish', 'autoset_featured');

这样,DUX主题就修改完了,保存即可看到效果。

本文参考了这两篇文章:

感谢原作者分享!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值