当前位置: 主机百科 » 资源 » 技术 » 正文

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主题就修改完了,保存即可看到效果。

未经允许不得转载:主机百科 » DUX主题实现缩略图随机显示

相关文章