从wordpress post获取图像(发布内容)

时间:2013-06-27 21:01:14

标签: php 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;

我需要显示每个帖子中的图片,以缩略图的形式显示在图库中。我搜索了很多,但无法弄清楚如何。

1 个答案:

答案 0 :(得分: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;
}

然后在您要用于打印图像的模板getTheFirstImage()中使用

$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