제목(the_title), 요약(the_excerpt) 등을 글자수로 그 길이를 요약합니다.

Explanation

워드프레스의 요약글은 뛰어쓰기를 기준으로 설정할 수 있지만 아무래도 한글은 뛰어쓰기로는 그 길이를 예상하기가 쉽지가 않다. 그래서 생각한 방법은 iconv, mb 모듈을 사용하여 워드프레스 타이틀(the_title()) 또는 요약글(the_excerpt())을 글자수로 요약할 수 있는 함수를 정의해봤다.
(절대 순수하게 내 머리에서 나온 방법은 아니고 wordpress.org의 support 인지.. 구글링에서 인지.. 에서 찾은 정보를 수정한 내용이다.)

소스보기

[functions.php]
 
//iconv 모듈이 설치되어 있다면,
if( !function_exists('cgs_text_length_sub') ){
    function jt_text_length_sub($text_fun, $text_length){
        $excerpt = $text_fun;
        $charlength = $text_length;
        if ( iconv_strlen( $excerpt ) > $charlength ) {
            $excerpt_more = apply_filters('excerpt_more', '');
            $subex = iconv_substr( $excerpt, 0, $charlength - iconv_strlen($excerpt_more));
            $exwords = explode( ' ', $subex );
            $excut =  -( iconv_strlen( $exwords[ count( $exwords ) - 1 ] ) );
            if ( $excut < 0 ) {
                return iconv_substr( $subex, 0, $excut ).$excerpt_more;
            } else {
                return $subex;
            }
        }else{
            return $excerpt;
        }
    }
}

//mb 모듈이 설치되어 있다면,
if( !function_exists('cgs_excerpt_length_sub') ){
    function cgs_excerpt_length_sub($excerpt, $excerpt_length){
        $excerpt = $excerpt;
        $charlength = $excerpt_length;
        if ( mb_strlen( $excerpt ) > $charlength ) {
            $excerpt_more = apply_filters('excerpt_more', '');
            $subex = mb_substr( $excerpt, 0, $charlength - mb_strlen($excerpt_more));
            $exwords = explode( ' ', $subex );
            $excut =  -( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
            if ( $excut < 0 ) {
                return mb_substr( $subex, 0, $excut ).$excerpt_more;
            } else {
                return $subex;
            }
        }else{
            return $excerpt;
        }
    }
}

if( !function_exists('custom_excerpt_length') ){
    function custom_excerpt_length( $length ) {
        return 100; //요약할 글자수를 100어절로 설정
    }
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
[사용할 템플릿 파일]

<?php echo cgs_excerpt_length_sub(get_the_title(), 80); ?>
<?php echo cgs_excerpt_length_sub(get_the_excerpt(), 80); ?>
 

선언한 함수 cgs_excerpt_length_sub()에 사용될 두번째 인자값의 크기는 mb 모듈을 사용할 지 iconv 모듈을 사용할 지에 따라 그 값의 크기가 많이 달라집니다.
아직 정확하게 많은 테스트를 해보진 않았지만, 함수의 두번째 인자의 크기를 세밀하게 조절해줘야 하고 요약할 제목이나 요약글에 한글, 영어, 특수문자 등.. 혼용되어 사용됐을때 약간의 오류를 포함하고 있습니다.

이전 댓글 2개
  1. cheolguso

    한글에서는 아직 테스트가 많이 부족한 정보여서요.. 보다 자세한 정보를 찾아보니, https://codex.wordpress.org/Function_Reference/get_the_excerpt 여기를 참고하시는게 좋을거 같아요. 댓글 남겨주셔서 너무 감사합니다 :D

  2. 이상종

    좋은 정보 감사합니다. 써먹어봐야겠네요 ^^