时间:2014-01-26所属栏目: WordPress教程 来源: 热度:
将wordpress文章里的第一张图片自动配置成为特色图片 thumbnail ,这是许多“懒人”急需知道的。
这是一段网上很“遍及”的代码了,但我照旧要贴一遍,以便往后本身查找起来利便。
复制下面的代码到 functions.php 中:
//Automatically Set the Featured Image in WordPress
function autoset_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', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');
在行使时留意让网站支持特色图片,并做好特色图片的尺寸限定,同样在 functions.php 里:
// This theme uses a custom image size for featured images, displayed on "standard" posts.
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 320, 320 ); // Unlimited height, soft crop