워드프레스 요약문에서 특정 HTML 태그를 유지시키는 방법

워드프레스 요약문(Excerpt)에는 특정 태그를 유지시키고자 하는 경우, 예를 들어 <p>, <br>, <a> 태그 등 특정 HTML 태그를 사용하고자 하는 경우 strip_tags() 함수를 사용하여 특정 태그를 활성화시키는 방법을 생각해볼 수 있습니다. strip_tags() 함수는 다음과 같이 사용됩니다.

strip_tags($contant,'허용할 태그');

예를 들어 다음과 같은 코드를 사용하면 숏코드 및 태그(허용 목록의 태그 제외)가 제거됩니다.

$content = get_the_content('');
$content = strip_shortcodes( $content );
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
$allowed_tags = '<p>,<a>,<em>,<strong>';
$content = strip_tags($content, $allowed_tags);

최종적으로 다음 함수를 사용할 수 있습니다.

function custom_wp_trim_excerpt($text) {
$raw_excerpt = $text;
if ( '' == $text ) {
$text = get_the_content('');

$text = strip_shortcodes( $text );

$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]&gt;', $text);

/***Add the allowed HTML tags separated by a comma.***/
/***허용할 HTML 태그를 콤마로 분리하는 형식으로 추가***/
$allowed_tags = '<p>,<a>,<em>,<strong>'; /*허용할 태그 목록 */
$text = strip_tags($text, $allowed_tags);

/***Change the excerpt word count.***/
/***요약문 단어수 변경***/
$excerpt_word_count = 60;
$excerpt_length = apply_filters('excerpt_length', $excerpt_word_count);

/*** Change the excerpt ending.***/
/*** 요약문 끝부분 변경***/
$excerpt_end = ' <a href="'. get_permalink($post->ID) . '">' . '&raquo; Continue Reading.' . '</a>';
$excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);

$words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
}
}
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_wp_trim_excerpt');

이 함수에 대한 자세한 설명은 여기를 참고하시기 바랍니다.  위 함수를 워드프레스 테마 폴더 내의 functions.php 파일에 추가하시면 됩니다. 직접 테스트는 하지 않았지만 이 함수를 통해 기본적인 개념을 이해할 수 있을 것입니다. (한글 요약문에서는 일부 한글이 깨질 수 있습니다.)

 

일부 글에 제휴 링크가 포함될 수 있으며 파트너스 활동으로 일정액의 수수료를 받을 수 있습니다.

댓글 남기기

* 이메일 정보는 공개되지 않습니다.