让WordPress 自动设置文章第一张图片为特色图像

 

2016-04-16_024149

WordPress的特色图像是一个很实用的功能,为每篇文章增加一个特色图像,可以使blog各个部分都更生动。比如首页每篇文章都有自己的缩略图,相关文章中用缩略图告诉用户这些文章的主题,或者在侧栏加一个特色文章功能,显示文章特色图像。

这里有一段很实用的代码,可以自动将文章中的第一张图片设置为特色图像,如果你手动设置了特色图像,可以覆盖这段代码。将下面的代码丢到当前主题的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');

关注【公众微信号】随时了解新动态!

Soyu Zom

您可能还喜欢...

3 条回复

  1. Incredible! This blog looks just like my old one!
    It’s on a entirely different subject but it has pretty much the same page layout
    and design. Great choice of colors! adreamoftrains best web hosting
    company

  2. Hi! I know this is kinda off topic nevertheless I’d figured I’d ask.
    Would you be interested in trading links or maybe
    guest authoring a blog post or vice-versa? My blog addresses a lot of the same topics
    as yours and I believe we could greatly benefit from each other.

    If you might be interested feel free to shoot me an email.
    I look forward to hearing from you! Fantastic blog by the way!

  3. web host说道:

    Terrific work! That is the kind of info that are meant to be shared across the net.
    Disgrace on Google for not positioning this post upper!
    Come on over and visit my website . Thanks =)

发表评论

电子邮件地址不会被公开。 必填项已用*标注