2011-03-15 56 views
5

我在我自己的網頁上使用The Loop來獲取WP的最後三個帖子。從wordpress文章中獲取有限的文本摘錄?

<?php 
     $args = array('numberposts' => 3); 
     $myposts = get_posts($args); 
     foreach($myposts as $post) : setup_postdata($post); ?> 

        <!-- DATE --> 
        <div class="date"> 
        <?php the_time('m F Y');?> 
        </div> 

        <!-- TITLE --> 
        <div class="title"> 
        <?php the_title(); ?> 
        </div> 

        <!-- SNIPPET --> 
        <div class="content"> 
        <?php the_excerpt(); ?> 
        </div> 
<?php endforeach; ?> 

一切工作正常 - 除了the_excerpt()。我需要大約15-20個來自帖子的純文本作爲預覽顯示。我如何去做這件事?

謝謝:)

回答

4

你可以嘗試使用類似這樣的東西搶後的第一個20個字,如果沒有可用的摘錄。

$content = get_the_content(); 
echo substr($content, 0, 20); 
+0

很抱歉,這是抓住人物沒有的話我不是考慮清楚,如果你想的話這裏是如何做到這一點[這裏]功能(http://www.nutt.net/2004/12/29/php-a-function-to-return-the-first-n-words-from-a-string/) – Tianbo84 2011-03-15 07:18:42

2

試試這個:

發表包含圖片:

$content = get_the_content(); 
$content = apply_filters('the_content', $content); 
$content = str_replace(']]>',']]&gt;', $content); 
echo substr(strip_tags($content),0,100); 

和沒有圖像:

$content = get_the_content(); 
echo substr($content, 0, 25); 
9

避免使用SUBSTR。爲什麼?

如果使用substr(),它可能會截斷結束的HTML標記並返回格式錯誤的HTML。

不要重新發明輪子!

WordPress 3.3以上有一個新的核心功能,稱爲wp_trim_words()

wp_trim_words參數分解:

wp_trim_words($text, $num_words, $more); 

$text 
    (string) (required) Text to trim 
    Default: None 

$num_words 
    (integer) (optional) Number of words 
    Default: 55 

$more 
    (string) (optional) What to append if $text needs to be trimmed. 
    Default: '…' 

實施例的用法:

<?php echo wp_trim_words(get_the_content(), 40, '...'); ?> 

<?php echo wp_trim_words(get_the_excerpt(), 20, '... read more...'); ?> 
0

將這個代碼中的functions.php

function new_excerpt_length($length) { 
    return 20;} 
add_filter('excerpt_length', 'new_excerpt_length'); 

而只是調用這個函數從模板頁或index.php文件

the_excerpt();