我们在wordpress开发过程中,如果主题设置文章列表获取的缩略图为文章的特色图像,那么我们就需要在编辑文章过程中为每篇文章添加特色图像,不过并不是没篇文章都需要一个独立的特色图像,有时候只是需要添加到文章的第一张图片作为特色图像而已,这样我们就希望在我们编辑文章时,添加图像后自动把第一张图片设置为特色图片。
相关文章:
- wordpress获取文章缩略图功能
- wordpress后台所有文章列表显示缩略图
wordpress自动添加特色图像的方法如下:
打开你主题的functions.php文件,在文件末尾添加如下代码:
if ( ! function_exists( 'fb_set_featured_image' ) ) {
add_action( 'save_post', 'fb_set_featured_image' );
function fb_set_featured_image() {
if ( ! isset( $GLOBALS['post']->ID ) )
return NULL;
if ( has_post_thumbnail( get_the_ID() ) )
return NULL;
$args = array(
'numberposts' => 1,
'order' => 'ASC', // DESC for the last image
'post_mime_type' => 'image',
'post_parent' => get_the_ID(),
'post_status' => NULL,
'post_type' => 'attachment'
);
$attached_image = get_children( $args );
if ( $attached_image ) {
foreach ( $attached_image as $attachment_id => $attachment )
set_post_thumbnail( get_the_ID(), $attachment_id );
}
}
}
保存后,进入后台编辑文件并上传图像,默认情况下文章的第一张图像就没自动添加到特色图像中,效果如下图所示: