2010-10-19 54 views
1

我想要從WP帖子中獲取全部圖片以創建幻燈片。用Google搜索了一圈,發現這段代碼來檢索並從後顯示圖像:如何顯示WordPress博客中的所有圖片?

function getImage($num) { 
    global $more; 
    $more = 1; 
    $link = get_permalink(); 
    $content = get_the_content(); 
    $count = substr_count($content, '<img'); 
    $start = 0; 
    for($i=1;$i<=$count;$i++) { 
     $imgBeg = strpos($content, '<img', $start); 
     $post = substr($content, $imgBeg); 
     $imgEnd = strpos($post, '>'); 
     $postOutput = substr($post, 0, $imgEnd+1); 
     $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);; 
     $image[$i] = $postOutput; 
     $start=$imgEnd+1; 
    } 
    if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; } 
    $more = 0; 
} 

正如你可以想像,那麼你使用的getImage(「1」)等獲得第1,第2,從圖像後等這不是創建幻燈片的理想選擇,因爲我不知道會有多少圖像。

有沒有辦法修改上面的代碼來獲取一個圖像數組來創建一個foreach循環,例如?對不起,如果我的邏輯有點缺陷,我不是一個PHP專家,因爲你可能已經猜到了。

在此先感謝您的幫助。

回答

2

這個代碼已經發現的所有影像,但只打印出1

試試這個變化,這應該呼應的所有圖像,而不是僅僅1.我沒有測試過這一點,但如果你原來的代碼工作,這應該。

function getImage() { 
    global $more; 
    $more = 1; 
    $link = get_permalink(); 
    $content = get_the_content(); 
    $count = substr_count($content, '<img'); 
    $start = 0; 
    for($i=1;$i<=$count;$i++) { 
     $imgBeg = strpos($content, '<img', $start); 
     $post = substr($content, $imgBeg); 
     $imgEnd = strpos($post, '>'); 
     $postOutput = substr($post, 0, $imgEnd+1); 
     $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);; 
     if(stristr($postOutput,'<img')) { echo '<a href="'.$link.'">'.$postOutput."</a>"; } 
     $start=$imgEnd+1; 
    } 
    $more = 0; 
} 

還有很多更多的清理可以在這個代碼上完成,但我只是修改了你的東西。

+0

這奏效了,謝謝你。就像我說的,我從一些博客中抓取了這個片段。如果有東西可以清理,我總是願意學習,如果你能解釋:) – Justine 2010-10-19 20:36:23

+0

一個問題:這個函數返回什麼?它是一個數組還是一堆代碼?我想創建一個使用這些圖像的foreach語句,但似乎並不像我能夠。 – Justine 2010-10-19 20:42:38

+0

這段代碼只是回顯你的所有圖片,它不返回它們。此代碼中的for循環已經遍歷所有圖像。如果你註釋掉'if'行,你可以關閉回顯,並把你自己的代碼放到循環中。或者你可以改變它,把每個'$ postOutput'放到一個數組中,並返回你可以循環的數組。 – 2010-10-19 21:51:51

1

在結束$ imgBeg到位$ imgEnd的代碼變化不大那麼它的做工精細

function getImage() { 
global $more; 
$more = 1; 
$link = get_permalink(); 
$content = get_the_content(); 
$count = substr_count($content, '<img'); 
$start = 0; 
for($i=1;$i<=$count;$i++) { 
    $imgBeg = strpos($content, '<img', $start); 
    $post = substr($content, $imgBeg); 
    $imgEnd = strpos($post, '>'); 
    $postOutput = substr($post, 0, $imgEnd+1); 
    $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);; 
    if(stristr($postOutput,'<img')) { echo '<a href="'.$link.'">'.$postOutput."</a>"; } 
    $start=$imgBeg+1; 
} 
$more = 0; 

}

相關問題