所以我已經尋找解決方案很長一段時間了。但不知何故找不到它。我需要的是一個顯示內容中特定數量的字符而不是特定數量的單詞的函數。因為單詞可能比其他單詞長,并且我希望保持帖子預覽中的樣式相同?,F在我還在用修剪詞:<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 = '…' ) {
$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?)?);

守候你守候我
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);

米脂
TA貢獻1836條經驗 獲得超3個贊
<p><?php echo substr(get_the_content(),0,15); ?></p>
如果該方法的輸出get_the_content()
是字符串,則可以使用substr()
method. 上面的示例輸出從索引 0 開始的 15 個字符
- 3 回答
- 0 關注
- 202 瀏覽
添加回答
舉報
0/150
提交
取消