亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

修剪內容中的字符而不是單詞 - Wordpress

修剪內容中的字符而不是單詞 - Wordpress

PHP
PIPIONE 2023-07-15 18:06:11
所以我已經尋找解決方案很長一段時間了。但不知何故找不到它。我需要的是一個顯示內容中特定數量的字符而不是特定數量的單詞的函數。因為單詞可能比其他單詞長,并且我希望保持帖子預覽中的樣式相同?,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 = '&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 關注
  • 202 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號