寫一段 WordPress 自動獲取第一張圖片為縮略圖的php 代碼

在WordPress中,可以使用以下PHP代碼來獲取文章的第一張圖片並將其作為文章的縮略圖

function get_first_image_as_thumbnail() {
global $post, $posts;
$first_image = '';
ob_start();
ob_end_clean();
if (preg_match('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches)) {
$first_image = $matches[1];
}
if (empty($first_image)) {
$attachments = get_children(array('post_parent'=>$post->ID, 'post_type'=>'attachment', 'post_mime_type'=>'image', 'numberposts'=>1));
if ($attachments) {
foreach($attachments as $attachment) {
$first_image = wp_get_attachment_url($attachment->ID);
}
}
}
if (!empty($first_image)) {
return $first_image;
} else {
return false;
}
}

此函數將獲取帖子內容中的第一張圖像,並將其返回作為縮略圖URL。如果文章中沒有圖像,則會嘗試獲取文章的附件中的第一張圖像。

要在文章模板中使用這個函數,可以將以下代碼插入到主題模板中的任何位置,例如single.php或content.php:

<?php $thumbnail = get_first_image_as_thumbnail(); ?>
<?php if ($thumbnail) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<img src="<?php echo $thumbnail; ?>" alt="<?php the_title_attribute(); ?>" />
</a>
<?php endif; ?>

這將創建一個縮略圖鏈接,其中縮略圖URL是使用上面的函數獲取的。

新媒體運營,新媒體代運營,cloudneo

原創文章,作者:超哥,如若轉載,請註明出處:https://www.chaoneo.cn/zh-hant/archives/3203.html

0 0 投票
五星評級

如果您覺得超哥分享對您有所幫助的話,記得打賞給我😀

訂閱
提醒
guest
0 評論
內聯反饋
查看所有評論
QQ客服
加我微信
電話聯繫
電子郵件
我們將24小時內回復。
取消
0
喜歡你的想法,請評論x
()
x