2013-04-08 15 views
1

我希望有人能幫助我。加載文字,而不是字母[WordPress的/ PHP的]

我正在安裝Wordpress的網站上工作。在首頁上,我有一個小div,我想用頁面ID從另一個頁面輸出前10個單詞。 目前它幾乎可以工作,但不是以10個字加載,而是以10個字母加載。

例子:
相反的:你好,我的名字是歐文,這是一個測試
它加載:你好我南

我在做什麼錯?

我用的functions.php下面的PHP:

if(!function_exists('getPageContent')) 
{ 
    function getPageContent($pageId,$num_words) 
    { 
     if(!is_numeric($pageId)) 
     { 
      return; 
     } 
     global $wpdb; 
     $nsquery = 'SELECT DISTINCT * FROM ' . $wpdb->posts . 
     ' WHERE ' . $wpdb->posts . '.ID=' . $pageId; 
     $post_data = $wpdb->get_results($nsquery); 
     if(!empty($post_data)) 
     { 
      foreach($post_data as $post) 
      { 
       $text_out=nl2br($post->post_content); 
       $text_out=str_replace(']]>', ']]>', $text_out); 
       $text_out = strip_tags($text_out); 
       return substr($text_out,0,$num_words); 

      } 
     } 
    }} 



我使用下面的字符串中要加載的內容:
(其中89是我的頁面ID )

echo getPageContent(89,10); 

回答

0

How to select first 10 words of a sentence? - 同樣的問題。只需使用implode(' ', array_slice(explode(' ', $text_out), 0, $num_words));代替substr($text_out,0,$num_words);

+0

這是與我上面貼出的代碼結合使用的最好,最快的解決方案,謝謝! – 2013-04-08 11:10:17

1

這WIL升提取前10個字的字符串

$text_out = "Hello my name is Erwin and this is a test and this is another test"; 
$num_words = 10; 
echo implode(' ', array_slice(explode(' ', $text_out), 0, $num_words)); 

輸出

Hello my name is Erwin and this is a test 
+0

謝謝你這麼多你的快速答案,但它是一個不同的問題。我知道我必須更改10到32加載前32個字母,但我想要的是,我可以加載的第一句話。 (因爲其他頁面中的文字可能每天都不一樣,我不想一直計算這些字母..我只是希望腳本自動加載在第一個字:) – 2013-04-08 09:54:12

+0

使用'strlen'函數它會自動計數字符串的長度,這裏是手冊http://php.net/manual/en/function.strlen.php – 2013-04-08 09:58:37

+0

所以你只需要第一個字作爲輸出? – 2013-04-08 10:02:56

0

有一個功能從WordPress的:

the_excerpt(); 

這不恰好。它顯示了......文章或頁面的摘錄以及最後的鏈接。您可以使用參數the_excerpt($length)稍微修改該功能來自定義長度。

來源:http://codex.wordpress.org/Function_Reference/the_excerpt

+0

感謝您的回答! 我發現了一個,但不知何故,我無法將其連接到某個pageID。它只會加載我當前所在頁面的前10個單詞,並且不會輸出來自另一個頁面 – 2013-04-08 10:13:49

+0

的內容,因爲您可能必須加載包含該功能的文件或類似的內容。 – aleation 2013-04-08 10:16:06

+0

我的php技巧對於你剛纔所說的低哈哈! – 2013-04-08 10:23:24

0

這裏$num_words = 10

這意味着如果你想整個字符串,那麼你必須呼應substr打破從性格0 to 10

字符串

echo getPageContent(89,32);