WordPress Excerpt count cannot filter characters 摘录计数无法过滤字符|摘要中文超多字符|教程|解决方案

本站使用的是WordPress的CN中文版本,在测试系统语言设置成English的过程中,发现文章的摘要变的字符数变得不受控制:

如果将WordPress的系统语言改回到中文的话,又会变的正常了。

经过搜索找到了一个解决方法。


解决方案

WordPress Excerpt 摘要在大多数语言字符中工作正常,但如果它在中文拼音语言中,则摘录不起作用。 由于汉字中的“无间距”,摘录计数无法过滤字符。 您可以使用以下中文修复:

将以下的代码复制加入到你的WordPress主题的functions.php中即可。

  • 纯中文博客把代码1加入您的主题的functions.php中即可,如果你是中文和非中文混合的博客,请将上面代码1.2都加入到您的主题的functions.php中。注意。第一个代码的字数是第一个代码字数的两倍。如代码中的50和100的关系。

代码1

function iesay_filter_chinese_excerpt( $output ) {
global $post;
//check if its chinese character input
$chinese_output = preg_match_all("/\p{Han}+/u", $post->post_content, $matches);
if($chinese_output) {
$output = mb_substr( $output, 0, 50 ) . '...';
}
return $output;
}
add_filter( 'get_the_excerpt', 'iesay_filter_chinese_excerpt' );

代码解释。第6行的50是中文字数设定,如果你是纯中文,50则代表50个字和标点符号。如果您的文章有英文摘要。你就需要在多使用下面的一个函数来定义英文默认的字数。


代码2

function ie_longer_excerpts( $length ) {
  // Don't change anything inside /wp-admin/
  if ( is_admin() ) {
    return $length;
  }
  // Set excerpt length to 140 words
  return 100;
}
// "999" priority makes this run last of all the functions hooked to this filter, meaning it overrides them
add_filter( 'excerpt_length', 'ie_longer_excerpts', 999 );

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注