IT/Wordpress

[워드프레스] 게시물 추출 글자 수 제한 처리하기

kang2oon 2012. 11. 19. 20:35
게시물을 메인이나 리스트 페이지를 만들어 출력할 경우 게시물의 모든 내용을 보여주는 것이 아닌 일부 내용을 추출하여 보여주게 됩니다. 이때 게시물의 일부 내용을 추출하는 워드프레스 함수를 사용하게 되는데요.. 
그 함수는 'the excerpt' 함수입니다. codex 사이트에서 상세한 사용법이나 해설이 나와있으니 참고하시기 바랍니다. [바로가기

예제를 보면 아래와 같이 테마의 function.php에 추가합니다.
function wpe_excerptlength_index($length) {
	return 50;
}

function wpe_excerpt($length_callback='', $more_callback='') {
	global $post;
	if(function_exists($length_callback)){
		add_filter('excerpt_length', $length_callback);
	}
	if(function_exists($more_callback)){
		add_filter('excerpt_more', $more_callback);
	}
	$output = get_the_excerpt();
	$output = apply_filters('	', $output);
	$output = apply_filters('convert_chars', $output);
	$output = '<p>'.$output.'</p>';
	echo $output;
}
이때 상단의 length에 반환되는 값이 제한하고자하는 글자 수입니다.
// Puts link in excerpts more tag
function new_excerpt_more($more) {
       global $post;
	return ' <a class="moretag" href="'. get_permalink($post->ID) . '">[ 전체보기... ]</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
또 위와 같은 구문을 이용하여 Continue reading... 과 같은 문구를 원하는 문구로 변경할 수 있습니다. 그런데  보통 테마를 변경할 경우 Child Theme를 이용하여 제작할 경우 Parent Theme로 인해 문구가 변경되지 않는 경우가 있습니다. 

이때는 아래의 구문을 추가하면 해결할 수 있습니다.
function child_theme_setup() { //child theme 이용시 추가
	// override parent theme's 'more' text for excerpts
	remove_filter( 'excerpt_more', 'twentyeleven_auto_excerpt_more' ); 
	remove_filter( 'get_the_excerpt', 'twentyeleven_custom_excerpt_more' );
}
add_action( 'after_setup_theme', 'child_theme_setup' );
게시물 작성시 요약 정보를 사용하지 않더라도 원하는 글자 수 만큼의 제한을 두어 index나 list 페이지 등을 구현할 수 있습니다. 

먼저 테마를 만들어 보시기 바랍니다.


반응형