wordpress文章第一个图片自动设置为特色图片

/* ------------------------------------------------------------------------- *
* 设置文章第一个图片自动为特色图片
/* ------------------------------------------------------------------------- */
function autoset_featured_image(){
    global $post;
    if (!isset($post->ID)) return;
    $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);
            }
        }/*else {
            //如果文章里没有图片,设置默认的一张图
            set_post_thumbnail($post->ID, '8888');
           //上面代码里的$post->ID, ‘8888’这个8888就是图片ID,自己在网站媒体库找一张图改一下ID吧。
        }*/
    }
}
add_action('save_post', 'autoset_featured_image');

发表回复

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




Enter Captcha Here :