写一段 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是使用上面的函数获取的。
原创文章,作者:超哥,如若转载,请注明出处:https://www.chaoneo.cn/archives/3203.html
如果您觉得超哥分享对您有所帮助的话,记得打赏给我😀