wordpress获取文章第一个图片
时间 : 2023-12-05 20:06:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性
最佳答案
在WordPress中,可以使用以下代码来获取文章的第一个图片:
```php
<?php
$post_id = get_the_ID(); // 获取当前文章的ID
$thumbnail_id = get_post_thumbnail_id($post_id); // 获取缩略图的ID
$thumbnail = wp_get_attachment_image_src($thumbnail_id, 'full'); // 获取缩略图的URL和尺寸
if ($thumbnail) {
$thumbnail_url = $thumbnail[0]; // 获取缩略图的URL
echo '<img src="' . $thumbnail_url . '" alt="">'; // 显示缩略图
}
?>
将以上代码插入到你的WordPress主题文件中,比如single.php或content.php,就可以在文章中显示第一个图片了。
请注意,如果文章没有设置缩略图,或者第一个图片不是缩略图,上述代码将不能获取到图片。如果你想要获取文章中的第一个图片,不管是否是缩略图,可以使用下面的代码:
```php
<?php
$post_id = get_the_ID(); // 获取当前文章的ID
$content = get_post_field('post_content', $post_id); // 获取文章内容
preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches); // 使用正则表达式匹配文章中的图片标签
if ($matches) {
$img_url = $matches[1]; // 获取图片URL
echo '<img src="' . $img_url . '" alt="">'; // 显示图片
}
?>
这段代码将从文章内容中提取第一个图片的URL,并显示在文章中。但请注意,这个方法可能会匹配到一些不是第一个图片的标签,所以需要谨慎使用。
其他答案
要在WordPress中获取文章的第一个图片,可以使用以下代码:
```php
<?php
global $post;
$first_image = '';
ob_start();
ob_end_clean();
// 获取文章内容
$content = $post->post_content;
// 从文章内容中提取第一个图片
$pattern = '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i';
preg_match($pattern, $content, $matches);
if ($matches) {
$first_image = $matches[1];
}
// 输出第一个图片链接
echo $first_image;
?>
将这段代码添加到你的主题文件(例如single.php)中,它将会获取当前文章的内容,并从中提取第一个图片的链接。然后你可以根据需求对这个链接进行进一步处理,例如显示图片或者添加到文章中。
https/SSL证书广告优选IDC>>
推荐主题模板更多>>
推荐文章