Dragon
主机之家测评主机之家测评  2021-04-09 14:25 主机之家测评 隐藏边栏 |   抢沙发  2 
文章评分 0 次,平均分 0.0

,这个主题看起来很不错,但是缩略图的设置很简单:如果设置了“特色图像”,就以“特色图像”作为缩略图;如果没有设置“特色图像”,则显示一幅默认的图片。经过研究,我最终实现了DUX 主题随机缩略图的显示:如果设置了“特色图像”,就以“特色图像”作为缩略图;如果没有设置“特色图像”,则自动调取文章内第一幅图片作为缩略图;如果文章内没有图片,则随机显示一幅图片。

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

首先修改 inc/fn.,打开 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 主题就修改完了,保存即可看到效果。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

发表评论

扫一扫二维码分享