2011-01-21 11 views
0

有沒有辦法抓取帖子的第一張圖片,並將其顯示爲首頁上帖子本身的縮略圖鏈接?我似乎無法弄清楚。不希望使用精選圖片功能。有沒有解決方法?任何幫助將非常感激。抓住WordPress Post的圖片並顯示它?


我可以使用下面的代碼來實現我想要的嗎?它似乎並不像我可以指定一個職位ID,但也許我錯了?

http://www.wordimpressed.com/wordpress/get-the-first-image-from-a-post-and-display-it/

我主要關注的是抓幾個帖子,並能夠在第一頁/主頁顯示。那可能嗎?

+0

RegExp呢? ;-) – thedom

+0

RegExp是否允許我只抓取幾個帖子?我可以在參數中指定一個帖子ID嗎? – TopChef

回答

0

你可以做到這一點通過兩個途徑:

function post_photo_count_attachments($post_id) { 

    $attachments = get_children(
     array('post_parent' => $post_id) 
    ); 

    return($attachments[0]); 

}

還是按查詢/ XPath的方法:

function post_photo_count_xpath($post_id) { 
    global $wpdb; 

    $post_id_safe = intval($post_id); 

    $html = $wpdb->get_row(
     "select * from {$wpdb->posts} where ID={$post_id_safe} limit 1" 
    ); 

    $doc = new DOMDocument(); 
    @$doc->loadHTML($html->post_content); 
    $path = new DOMXpath($doc); 
    $images = $path->query("//img"); 

    return($images->item(0)->getAttribute('src')); 
} 

的print_r()這些回報更詳細的信息。

0

我有一個類似的代碼在我的網絡循環中工作。它應該適合你!

 $content = $post->post_content; 
    $content = preg_replace('/\[.*\]/', '', $content); 
    $image = ''; 
    $x = stripos($content, '<img'); 
    if ($x !== false) { 
     $x = stripos($content, 'src="', $x); 
     if ($x !== false) { 
      $x += 5; 
      $y = strpos($content, '"', $x); 
      $image = substr($content, $x, $y-$x); 
     } 
    } 

它適用於我,所以如果你有問題,請告訴我。 ;)

+0

謝謝。我將如何使用此代碼從帖子中獲取圖片。假設帖子ID是3234 ...我能夠使用該ID並在首頁上顯示圖片嗎? – TopChef

+0

簡單! $ my_id = 3234; $ post = get_post($ my_id); – miduga