wp获取文章的第一张图片作为缩略图
七娃博客1,408人阅读
wp做主题的时候,懒人都不想再多点一下,为每篇文章手动添加缩略图,那么很多程序都是获取文章里面的第一张图片设置为缩略图,wp也可以这样设置,那么如何做?按照下面步骤就可以实现:
方法一:
1.fuction.php里面添加函数
function get_content_first_image($content){ if ( $content === false ) $content = get_the_content(); preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $content, $images); if($images){ return $images[1][0]; }else{ return false; } }
2.在需要的地方调用
<img src="<?php echo get_content_first_image(get_the_content()); ?>" alt="<?php the_title_attribute(); ?>" >
方法二:
1.function添加代码:
//获取第一张图 function catch_that_image() { global $post; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img*.+src=[\'"]([^\'"]+)[\'"].*>/iU', wp_unslash($post->post_content), $matches); if(empty($output)){ $first_img = "http://course.51qux.com/wp-content/uploads/2018/03/boke.png"; }else { $first_img = $matches [1][0]; } return $first_img; }
2.在需要的地方调用:
<?php echo catch_that_image(); ?>
评论 | 0 条评论
登录之后才可留言,前往登录