IT/Wordpress

[워드프레스] 포스트 첫 이미지 추출

kang2oon 2012. 11. 26. 20:30
오늘은 포스트의 특성 이미지에 이미지를 지정하지 않을 경우 리스트나 특정 페이지에 해당 게시물의 썸네일 이미지 부재로 인해 빈 공간으로 나오는 것을 방지해 줄 수 있도록 포스트의 첫 이미지를 추출하여 사용하는 방법을 살펴보겠습니다. 

우선 테마의 function.php 파일에 아래의 소스를 추가합니다.
// 포스트 첫 이미지 추출
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];

// no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.png";
}
return $first_img;
}
만약 해당 포스트에도 이미지가 존재하지 않을 경우를 대비해 특정 폴더에 default 이미지를 만들어 두어 사용할 수 있도록 작은 배려도 해두었습니다. 
 그리고 이미지를 출력하고자 하는 위치에 아래의 소스를 추가하여 원하는 형태로 출력을 조정하시면 됩니다.
<a href="<?php the_permalink() ?>">
	<?php
	if ( has_post_thumbnail() ) {
		the_post_thumbnail('medium', array('class' => 'blogimg'));
	} else {
		$thhumbimg = catch_that_image();
		echo '<div style="width:250px;height:128px;background:#f5f5f5 url('.$thhumbimg.') no-repeat 50% 50%;background-size:300px;"></div>';
	}
	?>
</a>
특성이미지가 존재하면 특성이미지를 사용하고 만약 특성이미지가 없다면 포스트의 첫 이미지를 사용할 수 있도록 수정된 부분입니다. 이렇게 하시면 특성이미지를 사용하면서 포스트의 첫 이미지를 사용할 수 도 있게 됩니다.


반응형