【问题标题】:WordPress excerpt character count not workingWordPress摘录字符数不起作用
【发布时间】:2018-03-14 18:05:28
【问题描述】:

我的循环如下所示:

<!-- loop for the posts here -->
<?php
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'category_name' => 'news'
    );
    $query = new WP_Query($args);
    while($query->have_posts()) : $query->the_post();
?>  
    <div class="news_box_content">
        <h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
        <figure><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure>
        <?php if($post->post_excerpt) { ?>
            <p><?php echo get_the_excerpt(); ?></p>
            <a href="<?php the_permalink(); ?>">Read more...</a>
        <?php } else {
            the_content('Read More');
        } ?>
    </div>
<?php endwhile; wp_reset_postdata(); ?>

我使用了一个函数来计算摘录长度,但它不起作用。

function custom_excerpt_length(){
   return 10;
}
add_filter('excerpt_length', 'custom_excerpt_length');

如何限制任何摘录的字符数?

【问题讨论】:

  • 您需要在循环中调用自定义摘录函数,即 custom_excerpt_length();而不是 get_the_excerpt();
  • 哎呀..是的,你是对的。

标签: wordpress


【解决方案1】:

不需要额外的过滤器

echo substr(get_the_excerpt(), 0,10);

【讨论】:

  • 它适用于摘录,但不适用于内容。这有效: 但这不起作用: echo substr(the_content('Read More'), 0,150);
【解决方案2】:

试试这个。我一直用这个

<?php 
      $content = get_the_content();
      $content = strip_tags($content);

      $dots = strlen(substr($content,0,50)) < 50 ? " " : "...";
      echo substr($content,0,50) . $dots;
      ?>

【讨论】:

    【解决方案3】:

    将此添加到您的functions.php文件中:

    function trim_excerpt( $exc ) {
        $exc_trimmed = substr( $exc, 0, 150 ) . '...';
        return $exc_trimmed;
    }
    add_filter( 'the_excerpt', 'trim_excerpt', 999 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 2013-12-19
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      相关资源
      最近更新 更多