2013-06-27 27 views
2

我需要在wordpress中获得该文章的第一张图片。 我有各种职位。所以对于新帖子,我可以设置精选图片。然而,有数千个旧帖子。我需要从这些帖子中提取第一张图片,以便我可以使用它们进行显示。从wordpress文章获取图片(发布内容)

我使用了http://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/的代码,我不认为它适合我。

global $post; 
$args = array('posts_per_page' => 10, 'category' => 6); 
$myposts = get_posts($args); 
foreach($myposts as $post) : setup_postdata($post); 
...... 
..... 
endforeach; 

我需要从缩略图的形式显示每个帖子的图像,如在一个画廊。我搜查了很多,但无法弄清楚如何。

回答

2

把这个在您的functions.php

function getTheFirstImage() { 
    $files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image'); 
    if($files) : 
     $keys = array_reverse(array_keys($files)); 
     $j=0; $num = $keys[$j]; 
     $image=wp_get_attachment_image($num, 'large', false); 
     $imagepieces = explode('"', $image); 
     $imagepath = $imagepieces[1]; 
     $thumb=wp_get_attachment_thumb_url($num); 
     echo "<img src='$thumb' class='thumbnail' />"; 
    endif; 
} 

要打印的图像

$args = array('posts_per_page' => 10, 'category' => 6); 
$myposts = get_posts($args); 
foreach($myposts as $post) : setup_postdata($post); 
    getTheFirstImage(); // Will print the image 
    ...... 
    ..... 
endforeach; 

Check this forum post在你的模板getTheFirstImage()函数然后使用。

+0

单个帖子怎么样。假设我想要获取ID已知的帖子的图片。 '$ post-> ID = 12'现在我想让post_content中的图像为这篇文章 – prakashchhetri

+0

然后只需传递ID'$ files = get_children('post_parent = 2&post_type = attachment&post_mime_type = image');' –

+0

@Heera:如何不能获得全尺寸的图像? –