четверг, 24 апреля 2014 г.

Auto Excerpt для WordPress

В WordPress есть замечательная функция the_excerpt() для вывода короткой цитаты поста.
Но бывает так, что надо вывести цитату определенной длины, не потеряв при этом форматирование.
    Но при попытке сохранить форматирование, обрезав контент, мы также обрезаем теги и получаем в итоге "кашу" на странице.
    Для решения проблемы нам надо закрыть все теги для обрезанного контента.
К счастью php, начиная с версии 5,4 поддерживает Tidy HTML - утилиту для очистки и восстановления HTML.


$tidy_config = array(
     'char-encoding' => 'utf8',
     'clean' => true,
     'output-html'     => true,
     'input-html'     => true,
     'wrap-attributes'     => true,
     'wrap-php'     => false,
     'wrap'         => 0);
     
   // закрываем открытые html tags
   $tidy = tidy_parse_string($out, $tidy_config, 'UTF8'); 
   $tidy->cleanRepair(); 
   $out = $tidy;

Вот окончательная функция для получения корректной цитаты с сохранением форматирования.
За основу я взял скрипт с сайта wp-kama.ru

function kama_excerpt($args=''){
 global $post;
  parse_str($args, $i);
  $maxchar   = isset($i['maxchar']) ?  (int)trim($i['maxchar'])  : 350;
  $text    = isset($i['text']) ?    trim($i['text'])  : '';
  $save_format = isset($i['save_format']) ? trim($i['save_format'])   : false;
  $echo   = isset($i['echo']) ?    false      : true;
  
  if($save_format == false)
   $save_format='<strong><p><ul><ol><li><br>';

 if (!$text){
  $out = $post->post_excerpt ? $post->post_excerpt : $post->post_content;
  $out = preg_replace ("!\[/?.*\]!U", '', $out ); //убираем шоткоды, например:[singlepic id=3]
  // для тега <!--more-->
  if( !$post->post_excerpt && strpos($post->post_content, '<!--more-->') ){
   preg_match ('/(.*)<!--more-->/s', $out, $match);
   $out = str_replace("\r", '', trim($match[1], "\n"));
   $out = preg_replace( "!\n\n+!s", "</p><p>", $out );
   $out = "<p>". str_replace( "\n", "<br />", $out ) ."</p>";   
    
   if ($echo)
    return print $out;
   return $out;
  }
 }

 $out = $text.$out;
 $out = strip_tags($out, $save_format);

 if ( iconv_strlen($out, 'utf-8') > $maxchar ){
  $out = iconv_substr( $out, 0, $maxchar, 'utf-8' );
  $out = rtrim($out);
  $out = preg_replace('@(.*)\s[^\s]*$@s', '\\1 ...', $out); //убираем последнее слово, ибо оно в 99% случаев неполное

  $tidy_config = array(
     'char-encoding' => 'utf8',
     'clean' => true, 
     'output-html'     => true,
     'input-html'     => true,
     'wrap-attributes'     => true,
     'wrap-php'     => false,
     'wrap'         => 0);
     
   // закрываем открытые html tags
   $tidy = tidy_parse_string($out, $tidy_config, 'UTF8'); 
   $tidy->cleanRepair(); 
   $out = $tidy;
 }
 if($echo) return print $out;
 return $out;
}
?>

Комментариев нет:

Отправить комментарий