2014-01-05 32 views
1

我編寫代碼以顯示相關帖子的縮略圖。如果相關的文章沒有縮略圖,它應該從他的內容顯示第一PICT:從相關帖子中捕獲第一張圖片

 $output .= "<a href=\"".get_permalink($related_post->ID)."\">"; 
      if(get_the_post_thumbnail($related_post->ID)) { 
       $output .= get_the_post_thumbnail($related_post->ID, $options['thumbnail_size']); 
      } else { 
       $output .= catch_image($related_post->ID); 
      } 
    $output .= "</a>"; 

和function.php我有這樣的功能:

function catch_image() { 
     global $post, $posts; 
     $first_img = ''; 
     ob_start(); 
     ob_end_clean(); 
     $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
     $first_img = $matches[1][0]; 

     if(empty($first_img)) { 
      $first_img = "url for noimage.jpg"; 
     } 

    return $first_img; 
    } 

但是,這給我的這個帖子只是第一個圖像,而不是來自相關帖子。我如何獲得我需要的內容?

回答

1

嘗試使用此功能:

function catch_image($post_id) { 

    $first_img = ''; 
    ob_start(); 
    ob_end_clean(); 
    $related_post = get_post($post_id); 
    $content = $related_post->post_content; 
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches); 
    $first_img = $matches[1][0]; 

    if(empty($first_img)) { 
     $first_img = "url for noimage.jpg"; 
    } 

    return $first_img; 
} 
+0

噢,謝謝!你是我的新超級英雄,再次感謝你! – Medardaosa

相關問題