获取特色图像如果为空则获取第一张图

2019-09-20 1,419 0

WordPress主题制作过程中经常要获得特色图像的URL以用来裁切或者呈现,但是有时候日志中不包含特色图像,比较好的方法是建立一个方程获得文章内容的第一张特色图像。

获得第一张图的方程在网上有很多,但是缺点是每次必须要用if去判断,有特色图像如何,没有特色图像如何。

所以为何我们不将判断的工作直接放进方程里,让这个方程去获取特色图像,没有的话就调用第一张图呢?

  1. /** Get First image */
  2. function get_first_image() {
  3. global $post, $posts;
  4. $featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
  5. if(empty($featured_img_url)){
  6. $first_img = '';
  7. ob_start();
  8. ob_end_clean();
  9. if($output = preg_match_all('/<img src="[\'&quot;]([^\'&quot;]+)[\'&quot;].*/">/i', $post->post_content, $matches)){
  10. $first_img = $matches [1] [0];
  11. }else{
  12. $first_img = '';
  13. };
  14. }else{
  15. $first_img= $featured_img_url;
  16. }
  17. return $first_img;
  18. }

把如上这组方程放入functions.php,然后在想调用的地方直接用 get_first_image() 就能直接输出特色图像的URL,如果没有特色图像,第一张图的URL将被输出。

例如

  1. $first_img = get_first_image(); // 将特色图或第一张图存进变量
  2. $title = get_the_title(); // 获得文章或页面标题
  3. if ( !empty($first_img) ) { // 如果特色图或第一张图不为空
  4. $blogthumburl = aq_resize( $first_img, 1170, 500, true, true, true ); //进行裁切并存入变量
  5. echo '
  6. <div class="card__image"><a href="'.$first_img.'" data-lightbox="gallery">'; //输出html把图放进其中
  7. echo '<img src="'.$blogthumburl.'" alt="'.$title.'" width="1170" height="500"></a></div>'; //继续输出
  8. }else{//如果特色图和第一张图都为空,则执行下面的内容
  9. }

有些人会在get_first_image()这个方程中增加一个判断,当全部为空时候输出一张默认图像,我认为是不恰当的,因为有时候页面的呈现上只需要文字,太多的默认图像,显得非常呆板。

另外,这个方程有个缺点,就是当文章中没有<img>标签,插入的是Wordpress相册的话,是无法获取相册的第一张图的,有待改进。

相关文章

宝塔开启系统防火墙,导致宝塔面板无法打开
谷歌广告插入附加宣传图片,可以降低每次的平均点击费用
使用Thumbnails插件处理图片缩略图及图片调用的php代码汇总
独立站和站群站点,分区别使用缓存和压缩插件
关于压缩html、css和js使网站加速的问题
linux服务器wordpress目录站群伪静态

发布评论

14 − 9 =