大白菜

  • 优惠汇总
  • linux闲谈
  • shell脚本
  • PHP编程
  • nginx
  • 随笔
分享你我
  1. 首页
  2. wordpress开发
  3. 正文

wordpress抓取缩略图

2025年2月20日 152点热度 0人点赞 0条评论

wordpress中是有thumbnail缩略图这个概念的

 

但是有时候并不想手动去设置缩略图

 

于是就有了这段代码,这段代码可以使用正则表达式

 

去抓取文章第一个img标签

 

然后作为缩略图进行展示

 

但是我发现这种方法有一个弊端

 

就是无法像缩略图那样去灵活的裁剪(我做了裁剪的尝试,但是似乎没有生效)

 

很多时候加载的都是原图

 

原图很大,一定程度上也是消耗了带宽

 

使网站的加载速度变得更慢

 

而且展示时候,可能也只能通过css中的height和width去限制大小

 

代码部分:

 

function post_thumbnail()
{
    global $post;
    // Ensure $post exists
    if (!$post) {
        return;
    }
    // Get Featured Image (Thumbnail)
    $img_id = get_post_thumbnail_id($post->ID);
    $img_url = wp_get_attachment_image_src($img_id, 'pic-h');
    if (!empty($img_url) && is_array($img_url)) {
        $img_url = $img_url[0];
    }
    // If Featured Image Exists
    if (!empty($img_url)) {
        echo '<img src="' . esc_url($img_url) . '" alt="' . esc_attr(get_the_title()) . '" />';
        return;
    }
    // Extract First Image from Post Content
    $content = $post->post_content;
    preg_match('/<img.*?src=["\'](.*?)["\'].*?>/i', $content, $matches);
    if (!empty($matches[1])) {
        $img_url = $matches[1];
        $attachment_id = attachment_url_to_postid($img_url);
        if ($attachment_id) {
            $img_data = wp_get_attachment_image_src($attachment_id, 'pic-h');
            foreach($img_data as $value){
                echo $value . '<br>';
            }
            $img_url = $img_data[0];
            echo $img_url;
        }
        echo '<img src="' . esc_url($img_url) . '" alt="' . esc_attr(get_the_title()) . '" />';
        return;
    }
    echo '<img src="' . esc_url( get_template_directory_uri() ) . '/img/thumb-medium.png"';
}
调用的时候只要使用post_thumbnail()代替the_post_thumbnail()方法即可
标签: 暂无
最后更新:2025年2月20日

bai

这个人很懒,什么都没留下

点赞
< 上一篇

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复
  • 2025 年 2 月
  • 2025 年 1 月
  • 2024 年 12 月
  • 2024 年 11 月
  • 2023 年 12 月
  • 2020 年 5 月
  • 2020 年 4 月

jquery LINUX nginx php SSL tls安全 traefik 输入法

  • wordpress抓取缩略图
  • wordpress裁剪缩略图
  • fstab自动挂载防止无法启动
  • web程序请求头安全加固
  • 提升SSL协议安全性
最近评论
一位WordPress评论者 发布于 5 年前(04月03日) 嗨,这是一条评论。 要开始审核、编辑及删除评论,请访问仪表盘的“评论”页面。 评论者头像来自Grav...

COPYRIGHT © 2020-2025 大白菜的博客. ALL RIGHTS RESERVED.

冀ICP备18004313号-1