从内容而不是单词中修剪字符 - 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; ?>

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

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自动换行和爆炸来实现目标。

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

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

如果你想要字符串中没有任何 HTML 的 15 个字符,你可以分步骤完成:

首先获取字符串并使用 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 个字符

最新更新