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

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

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

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

$html = sprintf('DUX主题实现缩略图随机显示', get_stylesheet_directory_uri() . '/img/thumbnail.png', $class);

修改为:

$random = mt_rand(1, 20);
$html = sprintf('DUX主题实现缩略图随机显示', 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主题就修改完了,保存即可看到效果。

本文参考了这两篇文章:

http://www.dedewp.com/2568.html

http://www.ymjihe.com/1753.html

感谢原作者分享!

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/250957.html

(0)
上一篇 2022年5月1日 00:13
下一篇 2022年5月1日 00:13

相关推荐

发表回复

登录后才能评论