提问者:小点点

从内容中修剪字符而不是单词-Wordpress


所以我一直在寻找解决办法。 但不知怎么找不到。

我需要的是一个从内容中显示特定数量字符的函数,而不是具体的字数。 因为单词可以比其他单词更长,我想保持样式从后预览相等。

现在我还在用修剪的词:

<p><?php echo wp_trim_words( get_the_content(), 15 ); ?></p>

有人知道我如何从一个帖子的内容中修剪字符而不是字数吗?

提前谢谢你!

更新:

以下是我的完整帖子部分:

    <?php
      $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'category__in' => array(2, 3),
        'post__not_in' => array( $post->ID ),
      );
    ?>
    <?php $query = new WP_Query($args); ?>
    <?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>

      <a href="<?php the_permalink();?>">
        <div class="post">
          <?php $thumb = get_the_post_thumbnail_url(); ?>
          <div class="post-image" style="background-image:url('<?php echo $thumb;?>');"></div>
          <div class="post-prev">
            <?php
            foreach (get_the_category() as $category){
              echo "<span>";
              echo $category->name;
              echo "</span>";
            } ?>
            <h2>
              <?php
                $thetitle = $post->post_title;
                $getlength = strlen($thetitle);
                $thelength = 20;
                echo substr($thetitle, 0, $thelength);
                if ($getlength > $thelength) echo "..";
              ?>
            </h2>
            <p><?php echo wp_trim_words( get_the_content(), 15 ); ?></p>
            <span class="btn">Lees verder</span>
          </div>
        </div>
      </a>

    <?php endwhile; wp_reset_postdata(); else : ?>
      <p><?php _e("Geen content gevonden.."); ?></p>
    <?php endif; ?>

共2个答案

匿名用户

如果您希望字符串中只有15个字符而不包含任何HTML,则可以按以下步骤完成:

首先获取字符串并使用strip_tags()删除HTML:

$content = strip_tags(get_the_content());

然后使用substr()从现在没有HTML的字符串中获取前15个字符:

echo substr($content, 0, 15);

那样就行了。

您也可以使用一行代码:

echo substr(strip_tags(get_the_content()), 0, 15);

匿名用户

<p><?php echo substr(get_the_content(),0,15); ?></p>

如果方法get_the_content()的输出是一个字符串,那么您可以使用substr()方法。 上面的示例输出从索引0开始的15个字符