WordPress自动添加文章特色图像缩略图

WordPress的特色图像是一个很实用的功能,可以在文章列表中为每篇文章添加一张缩略图。但特色图像需要在编辑文章时手动添加很不方便,下面的代码可自动将文章中的第一张图片设置为特色图像。

将下面的代码添加到当前主题的functions.php中:

function wpforce_featured() {
    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);
            }
        }
    }
}  https://end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

如果当前文章中没有图片,但又想显示一张默认的缩略图该怎么办,可以将上面的代码修改一下,调用媒体库中某个图片作为默认的缩略图:

function wpforce_featured() {
    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);
            }
        } else {
            set_post_thumbnail($post->ID, '666666');
        }
    }
}  https://end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

其中的数字666666,是媒体库中某个图片附件的ID号。

WordPress技巧

修复mysqli_query(): (HY000/1194)·······wp-db.php on line 1877

2017-10-26 14:14:28

WordPress技巧

WordPress设置浏览器缓存(Leverage browser caching)

2017-12-14 15:19:21

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索