【问题标题】:How to get a get_the_content word limit如何获得 get_the_content 字数限制
【发布时间】:2018-11-09 12:14:30
【问题描述】:

我有一个 get_the_content() Wordpress 代码,如下所示。我想强制代码执行以下操作:

  • 不要将空标签显示为 nbsp; (现在工作)
  • 只显示有限的字数(不知道如何)

我将此代码添加到我的 home.php 中:

<?php 
$content = get_the_content('Read more');
$content = str_replace('&nbsp;'," ", get_the_content());
$content = preg_replace( '/\s+/', ' ', $content );
echo $content; 
?>

它有效,但我现在只想显示有限数量的单词。 $char_limit 和 wp_trim_words() 之类的所有解决方案都不是我要寻找的解决方案,因为它们弄乱了博客文章。

我能做什么?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    使用这个方便的实用功能来限制此处Get first 100 characters from string, respecting full words中描述的单词的字数

    function truncate($text, $length) {
       $length = abs((int)$length);
       if(strlen($text) > $length) {
          $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
       }
       return(str_replace('&nbsp;'," ", $text));
    }
    

    传递像

    这样的值
    $content = get_the_content('Read more');
    print_r(truncate($content, 180));
    

    【讨论】:

      【解决方案2】:
      function limitText($text, $limit)
      {
          $count = strlen($text);
          if ($count >= $limit) {
              $text = substr($text, 0, strrpos(substr($text, 0, $limit), ' ')) . '...';
      
              return $text;
          } else {
              return $text;
          }
      }
      

      还有回声

       <?= limitText(get_the_content(), 30); ?>
      

      【讨论】:

        猜你喜欢
        • 2023-03-11
        • 2013-04-04
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        • 2021-04-16
        • 1970-01-01
        • 2010-11-29
        • 1970-01-01
        相关资源
        最近更新 更多