2012-05-14 43 views

回答

2

考慮到某些Feed結構不同,我沒有明確的方式來做到這一點,我知道。這是我能夠做到it.First看看這篇文章:

How to Display Thumbnail from WordPress RSS feed using SimplePie?

我能夠複製並粘貼代碼,並

我沒有使用Wordpress做一些細微的變化,但它幫助我瞭解需要做些什麼。

在feed-> init()後插入此代碼。

//This function will get an image from the feed 

function returnImage ($text) { 
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8'); 
    $pattern = "/<img[^>]+\>/i"; 
    preg_match($pattern, $text, $matches); 
    $text = $matches[0]; 
    return $text; 
} 


    //This function will filter out image url which we got from previous returnImage() function 

    function scrapeImage($text) { 
     $pattern = '/src=[\'"]?([^\'" >]+)[\'" >]/'; 
     preg_match($pattern, $text, $link); 
     $link = $link[1]; 
     $link = urldecode($link); 
     return $link; 

    } 

現在你要調用的功能,因此它搜索的說明,或在我的情況的內容,找到img標籤,並正確結構輸出。這是我的代碼看起來像:

foreach ($feed->get_items(0 , 3) as $item): 
    $feedDescription = $item->get_content(); 
    $image = returnImage($feedDescription); 
    $image = scrapeImage($image); 
    $image_url= $item->get_permalink(); 
    $description = $item->get_description(); 
?> 
     <div class="item"> 
      <h4><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4> 
      <div class="image-box"><?php echo '<a href="' . $image_url . '"><img src="' . $image . '" /></a>'."\n";?></div> 
      <p><?php echo $description ?></p> 
      <p><a href="<?php echo $item->get_permalink(); ?>">Continue Reading</a></p> 
     </div> 

    <?php endforeach; ?> 

這可能需要一些迷戀,但一旦你知道你的img標籤的飼料中存在,就可以得到了SimplePie解析飼料和功能會發現標籤和格式,所以它是HTML的準備。

如果只拉一個職位,你可以編輯你的循環:

foreach ($feed->get_items(0 , 1) as $item): 

第一個數字(0)爲出發點,0是最新的帖子。第二個數字(1)是需要拉多少個帖子。由於您只需要一張圖片,因此您希望該數字爲1.

+0

hmm.nice謝謝。 –

1

也許您想在客戶端執行此操作。然後用jQuery很容易。 比方說,在你的JavaScript您的項目,內容是這樣的

var content = '<div><a href="http://kwout.com/cutout/b/es/y2/ukn_rou_sha.jpg" 
imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"> 
<img border="0" height="239" src="http://kwout.com/cutout/b/es/y2/ukn_rou_sha.jpg" 
width="320"></a>Erat austro rerum.</div>'; 

然後你就可以輕鬆地識別並與jQuery的選擇內容中隔離圖像。例如使用

$(content).find('img:first'); //find the FIRST image inside an element or 
$(content).find('a:first');  //take the hyperlink AND the image 

如果不是裏面的內容第一圖像或內容比這個例子中(主要是;-)更復雜 - 無後顧之憂 - 然後一些其他選擇將這樣的伎倆。請參閱jquery.com上的文檔以獲取更多信息。

通過這種方式,我刪除了元素,向內容中的不同元素添加了一些或添加的類,以按照我的方式顯示帖子。