为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
PIPIONE 2023-07-15 18:06:11
所以我已经寻找解决方案很长一段时间了。但不知何故找不到它。我需要的是一个显示内容中特定数量的字符而不是特定数量的单词的函数。因为单词可能比其他单词长,并且我希望保持帖子预览中的样式相同。现在我还在用修剪词:<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; ?>
查看完整描述

3 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

为了避免删减单词,我使用以下自定义函数:


function theme_truncate( $string, $length = 100, $append = '&hellip;' ) {

$string = trim( $string );


if ( strlen( $string ) > $length ) {

    $string = wordwrap( $string, $length );

    $string = explode( "\n", $string, 2 );

    $string = $string[0] . $append;

}


return $string;}

它是利用PHP的wordwrap和explode来达到目的的。

稍后您可以像这样调用该函数:

echo esc_html( theme_truncate( get_the_content(), 15 ) );


查看完整回答
反对 回复 2023-07-15
?
守候你守候我

TA贡献1802条经验 获得超10个赞

如果您想要字符串中正好有 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);


查看完整回答
反对 回复 2023-07-15
?
米脂

TA贡献1836条经验 获得超3个赞

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

如果该方法的输出get_the_content()是字符串,则可以使用substr()method. 上面的示例输出从索引 0 开始的 15 个字符


查看完整回答
反对 回复 2023-07-15
  • 3 回答
  • 0 关注
  • 97 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信