自动为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);
}
}
}
} //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, '414');
}
}
} //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');
其中的数字414,是媒体库中某个图片附件的ID号。
特色图像只适合不在乎空间流量和大小的用户使用,因为每张图片都会裁剪成多张大小不同的缩略图方便在不同的位置调用,最主要的是不支持外链,很浪费空间....
您或许对下面这些文章有兴趣: 本月吐槽辛苦排行榜
- 如何快速在WordPress中生成网站缩略图?Browser Shots插件与代码法
- WordPress评论插入图片与附件-直接添加代码法和安装评论图片插件法
- WordPress表格插件TablePress:支持排序,分页,搜索和导入导出CSV
- 优秀的WordPress在线问答插件AnsPress安装与使用
- 使用Poedit汉化.PO和编译.MO文件-附汉化WordPress主题和插件
- WordPress邀请注册插件:Easy Invitation Codes,Secure Invites和WP-Invites
- WordPress手机主题移动版优化方案-WPtouch安装使用及百度移动适配设置
- 国外优秀网站模板平台Themeforest付费WordPress主题购买下载安装方法