【问题标题】:Get a limited, text-only excerpt from a WordPress post?从 WordPress 帖子中获取有限的纯文本摘录?
【发布时间】:2011-07-15 12:16:39
【问题描述】:

我在自己的主题模板中使用“循环”来获取来自 WordPress 的最后三个帖子。

<?php
$args = array( 'numberposts' => 3 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>

    <!-- DATE -->
    <div class="date">
    <?php the_time('m F Y');?>
    </div>

    <!-- TITLE -->
    <div class="title">
    <?php the_title(); ?>
    </div>

    <!-- SNIPPET -->
    <div class="content">
    <?php the_excerpt(); ?>
    </div>

<?php endforeach; ?>

一切正常 - 除了the_excerpt()。我需要帖子中大约 15-20 字的纯文本来显示为预览,而不是完整的摘录或整个帖子的内容正文。我该怎么做?

【问题讨论】:

    标签: php arrays wordpress function foreach


    【解决方案1】:

    如果没有可用的摘录,您可以尝试使用类似的方法来获取帖子的前 20 个字。

    $content = get_the_content();
    echo substr($content, 0, 20);
    

    【讨论】:

    • 对不起,这是要抓住字符而不是单词我没有想清楚,如果你想要单词,这里有一个函数here
    【解决方案2】:

    试试这个:

    帖子包含图片:

    $content = get_the_content();
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>',']]&gt;', $content);
    echo substr(strip_tags($content),0,100); 
    

    并且没有图片:

     $content = get_the_content();
     echo substr($content, 0, 25);
    

    【讨论】:

      【解决方案3】:

      避免使用substr()。为什么?

      substr() 根据字符数截断,而不是整个单词,最后一个单词很可能会被截断。它还可能截断结束 HTML 标记并返回格式错误的 HTML,从而搞砸您的其余布局。

      不要重新发明轮子!

      WordPress 3.3 及以上版本有一个新的核心功能,称为wp_trim_words()

      参数分解:

      wp_trim_words($text, $num_words, $more);
      
      
      $text
          (string) (required) Text to trim
          Default: None
      
      $num_words
          (integer) (optional) Number of words
          Default: 55
      
      $more
          (string) (optional) What to append if $text needs to be trimmed.
          Default: '…'
      

      示例用法:

      <?php echo wp_trim_words(get_the_excerpt(), 30, '...'); ?>
      
      <?php echo wp_trim_words(get_the_content(), 50, '... read more &gt;'); ?>
      

      【讨论】:

      • 太棒了!这是做到这一点的“WordPress 方式”。
      【解决方案4】:

      将此代码放在functions.php中

      function new_excerpt_length($length) {
        return 20;}
      add_filter('excerpt_length', 'new_excerpt_length');
      

      只需从模板页面或 index.php 文件中调用此函数

      the_excerpt();
      

      【讨论】:

      • 如果您想在站点的任何地方修改摘录长度,这是最好的方法,但听起来 OP 只想在一个地方进行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多