从帖子中获取第一个图片网址? [英] Geting the first image url from a post?

查看:23
本文介绍了从帖子中获取第一个图片网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个动态网站,我有一个包含一些新闻的数据库,我想从帖子内容中获取第一张图片新闻是用 wordpress 添加到这个数据库中的,因为你知道 wordpress 图片在 post_content 中.

I am trying to create a dynamic website, I have a database with some news, and I wanted to get the first image from the post content The news are added to this database with wordpress, as you know wordpress images are inside the post_content.

请您帮我获取帖子的第一张图片并显示链接.

Please can you help me to get the first image of the post and dispay the link.

谢谢

推荐答案

把这个放在你的functions.php文件中:

Put this in your functions.php file:

function get_first_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(empty($first_img)){ //Defines a default image
        $first_img = "/images/default.jpg";
    }
    return $first_img;
}

然后只需调用页面上的函数即可获取帖子的第一张图片,如下所示:

and then simply call the function on the page you need to get the first image of the post like this:

<?php echo get_first_image() ?>

这篇关于从帖子中获取第一个图片网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆