WordPress设置文章的第一张图片为特色图片的图文教程

很多新手刚开始接触 WordPress 的时候,很多都不懂,每次发布文章都要自己设置特色图片,但是总是感觉操作很麻烦,毕竟自己的一篇文章上传了这么多图片,有没有更好的办法呢,比如设置文章的第一张图片为特色图片。接下来虾皮路就给大家介绍一下 WordPress 设置文章的第一张图片为特色图片的图文教程。 大家每次写文章的时候是不是发现每次都要设置特色图片很烦呢,如下 其实没有这么复杂,因为每篇文章只要上传了图片都有缩略图,我们都可以调用的,只是调用的方法要修改代码,如下: 首先打开模板文件默认主题下的 functions.php 文件,然后找到最下面,放入如下代码。 /* ------------------------------------------------------------------------- * * 设置文章第一个图片自动为特色图片 /* ------------------------------------------------------------------------- */ function autoset_featured_image(){ global $post; $already_has_thumb = has_post_thumbnail($post->ID); if (!$already_has_thumb){ $attached_image = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1"); if ($attached_image){ foreach ($attached_image as $attachment_id => $attachment) { set_post_thumbnail($post->ID, $attachment_id); } } } } add_action('the_post', 'autoset_featured_image'); add_action('save_post', 'autoset_featured_image'); add_action('draft_to_publish', 'autoset_featured_image'); add_action('new_to_publish', 'autoset_featured_image'); add_action('pending_to_publish', 'autoset_featured_image'); add_action('future_to_publish', 'autoset_featured_image'); 注意: 如果你手动设置了特色图片,这段代码就不起作用,会默认到你设置的特色图片,无需担心。

2022年11月14日 · 1 分钟 · 诚哥博客