WordPress自动为文章设置特色图像

有的同学不喜欢每次写文章都手动设置一遍特色图像,下面的代码可以帮你解决这个问题:自动将文章中的第一张图片设置为特色图像,如果你手动设置了特色图像,那么会优先选择你手动设置的图像,这样就不会和代码相冲突了。
开启特色图像/缩略图

  1. // 开启特色图并设置默认大小
  2. add_theme_support ( 'post-thumbnails' );
  3. set_post_thumbnail_size ( 160 );

自动设置特色图像
丢到functions.php里面。

  1. function autoset_featured() {
  2.     global $post;
  3.     $already_has_thumb = has_post_thumbnail($post->ID);
  4.         if (!$already_has_thumb)  {
  5.         $attached_image = get_children( “post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1” );
  6.             if ($attached_image) {
  7.                 foreach ($attached_image as $attachment_id => $attachment) {
  8.                 set_post_thumbnail($post->ID, $attachment_id);
  9.                 }
  10.             }
  11.         }
  12.  }
  13. add_action(‘the_post’, ‘autoset_featured’);
  14. add_action(‘save_post’, ‘autoset_featured’);
  15. add_action(‘draft_to_publish’, ‘autoset_featured’);
  16. add_action(‘new_to_publish’, ‘autoset_featured’);
  17. add_action(‘pending_to_publish’, ‘autoset_featured’);
  18. add_action(‘future_to_publish’, ‘autoset_featured’);

via:solagirl

0 0 投票数
文章评分
订阅评论
提醒
guest

0 评论
内联反馈
查看所有评论
0
希望看到您的想法,请您发表评论x