WordPress文章列表随机显示缩略图[wp自动缩略图]

微信扫一扫,分享到朋友圈

WordPress文章列表随机显示缩略图[wp自动缩略图]
收藏 00

在使用WordPress发布文章的时候,很多主题默认取文章第一个图片为缩略图,使用timthumb.php函数自动调整缩略图大小,并生成缓存文件,目前国内外大部分WordPress主题都采用此方法生成缩略图。这一方法的缺点是无法截取外链图片,处理起来特别麻烦。

方法1:

没有缩略图就指定固定的一张图片为缩略图

<?php if ( get_post_meta($post->ID, 'thumbnail', true) ) : ?>
<?php $image = get_post_meta($post->ID, 'thumbnail', true); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo $image; ?>" alt="<?php the_title(); ?>"/></a>
<?php else: ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/img.jpg" alt="<?php the_title(); ?>"/></a>
<?php endif; ?>

讲解

<img src="<?php bloginfo('template_directory'); ?>/images/img.jpg" alt="<?php the_title(); ?>"/>

为核心代码,指定当前模版文件下images文件夹中的img.jpg为缩略图,这个方法能实现指定固定一张图片为缩略图。

但是在实际使用中,我们很多文章都没有图片的话,只用一张图片来当缩略图就显得不美观,建议用方法2

方法2

在默认占位图链接位置添加一句rand()函数就可随机调用特定目录下的多个图片,实现文章列表随机调用缩略图,具体代码为:

<?php if ( get_post_meta($post->ID, 'thumbnail', true) ) : ?>
<?php $image = get_post_meta($post->ID, 'thumbnail', true); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo $image; ?>" alt="<?php the_title(); ?>"/></a>
<?php else: ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/random/img<?php echo rand(1,5)?>.jpg" alt="<?php the_title(); ?>"/></a>
<?php endif; ?>

注释

/images/random/img<?php echo rand(1,5)?>.jpg

前面的img是图片的名称,我们可以新建几个名称为:img1.jpg, img2.jpg,img3.jpg,img4.jpg,img5.jpg的图片,放到使用的主题的/images/random/(图片所在的位置,可根据实际修改。)目录中,也可以是其它格式的图片,数字5是预设的的随机图片数量,可以修改此数字,并相应增加随机图片数量。

将上面的代码添加到要调用缩略图的位置即可完美实现。

一个热爱互联网的咸鱼
下一篇

WordPress博客文章随机添加图片并自动缩略图

你也可能喜欢

发表评论

您的电子邮件地址不会被公开。 必填项已用 * 标注

提示:点击验证后方可评论!

插入图片

热门

    抱歉,30天内未发布文章!
返回顶部