wordpress自动添加特色图像


我们在wordpress开发过程中,如果主题设置文章列表获取的缩略图为文章的特色图像,那么我们就需要在编辑文章过程中为每篇文章添加特色图像,不过并不是没篇文章都需要一个独立的特色图像,有时候只是需要添加到文章的第一张图片作为特色图像而已,这样我们就希望在我们编辑文章时,添加图像后自动把第一张图片设置为特色图片。
相关文章:

  • wordpress获取文章缩略图功能
  • wordpress后台所有文章列表显示缩略图

wordpress自动添加特色图像的方法如下:
打开你主题的functions.php文件,在文件末尾添加如下代码:

  1. if ( ! function_exists( 'fb_set_featured_image' ) ) {
  2.     
  3.     add_action( 'save_post', 'fb_set_featured_image' );
  4.     function fb_set_featured_image() {
  5.             
  6.             if ( ! isset( $GLOBALS['post']->ID ) )
  7.                 return NULL;
  8.                 
  9.             if ( has_post_thumbnail( get_the_ID() ) )
  10.                 return NULL;
  11.             
  12.             $args = array(
  13.                 'numberposts'    => 1,
  14.                 'order'          => 'ASC', // DESC for the last image
  15.                 'post_mime_type' => 'image',
  16.                 'post_parent'    => get_the_ID(),
  17.                 'post_status'    => NULL,
  18.                 'post_type'      => 'attachment'
  19.             );
  20.             
  21.             $attached_image = get_children( $args );
  22.             if ( $attached_image ) {
  23.                 foreach ( $attached_image as $attachment_id => $attachment )
  24.                     set_post_thumbnail( get_the_ID(), $attachment_id );
  25.             }
  26.             
  27.     }
  28.     
  29. }

保存后,进入后台编辑文件并上传图像,默认情况下文章的第一张图像就没自动添加到特色图像中,效果如下图所示:
set-featured-image