首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >wordpress发布第一张图片

wordpress发布第一张图片
EN

Stack Overflow用户
提问于 2013-02-14 16:22:15
回答 1查看 395关注 0票数 0

我如何过滤我的帖子,特色或在WordPress中的第一个图像,并在显示前添加到主题的css类。我看到我可以在我的functions.php中使用API中的add_filter()函数,但是我在获取每个帖子的第一张图片时遇到了问题。

代码语言:javascript
复制
<a href="http://localhost/wordpress/wp-content/uploads/2012/10/test.jpg">
<img class="alignnone size-full wp-image-95" width="540" height="300" alt="dell-vs-apple" src="http://localhost/wordpress/wp-content/uploads/2012/10/dell-vs-apple1.jpg">
</a>


<div class = "my_class">
<a href="http://localhost/wordpress/wp-content/uploads/2012/10/dell-vs-apple1.jpg">
<img class="alignnone size-full wp-image-95" width="540" height="300" alt="dell-vs-apple" src="http://localhost/wordpress/wp-content/uploads/2012/10/dell-vs-apple1.jpg">
</a>

EN

回答 1

Stack Overflow用户

发布于 2013-02-14 21:11:14

这是从post中获取第一张图片的一种方法。

代码语言:javascript
复制
  // Get URL of first image in a post
    function o99_find_first_post_image() {
        global $post, $posts;
        $first_img = '';
        ob_start();
        ob_end_clean();
        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
        $first_img = $matches [1] [0];

        // if no image found we can choose to display some default image instead
        if(empty($first_img)){
            $first_img = "/images/default.jpg";// path to default image
        }
        return $first_img;
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14870528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档