2011-11-13 73 views
1

试图从帖子中获取第一张图片,但我的php代码不会返回任何内容,有帮助吗?Wordpress从帖子中获取第一张图片

<?php while ($browndog_blog->have_posts()) : $browndog_blog->the_post();      
    $args = array(
    'numberposts' => 1, 
    'post_mime_type' => 'image', 
    'post_parent' => $post->ID, 
    'post_status' => null, 
    'post_type' => 'attachment' 
    ); 

    $attachments = get_children($args); 

    //print_r($attachments); 

    if ($attachments) { 
     foreach($attachments as $attachment) { 
      $image_attributes = wp_get_attachment_image_src($attachment->ID, 'thumbnail') ? wp_get_attachment_image_src($attachment->ID, 'thumbnail') : wp_get_attachment_image_src($attachment->ID, 'full'); 

      echo '<a href="'.get_permalink($post->ID).'"><img src="'.wp_get_attachment_thumb_url($attachment->ID).'"></a>'; 
      echo '<p>'.get_the_excerpt($post->ID).'</p>'; 
      echo '<p><a href="'.get_permalink($post->ID).'">Read More</a></p>'; 
     } 
    } 
endwhile; ?> 

不知道发生了什么事情错了,因为我使用了一个类似的代码来获取所有图像附件,而不是只有一个,那工作正常。

+0

[如何获得第一张图片与WP帖子相关联]的可能重复?(http://stackoverflow.com/questions/2332979/how-to-get-the-first-image-assoc-with-a -wp-POST) – hakre

回答

0

我想我只是做了同样的事情,你正在寻找做...我不会声称是一个上师,但这是我做了什么来做到这一点工作,并与运气,你将能够适应它符合你的需求。

$image_id=get_post_thumbnail_id(); 
$image_url = wp_get_attachment_image_src($image_id,’large’); 
$image_url=$image_url[0]; 

基本上数组中的第一个图像的缩略图,按我的理解,所以这就是为什么我第一次抢缩图ID,然后用它来获取大版本的图像。

1

get_children()仅返回已直接上传到该帖子的图片。如果图像已附加到给定的帖子,它不会被认为是它的孩子,因此不会被上述功能返回。

一个简单的方法来检查一个职位的孩子是登录到仪表板并转到帖子,编辑帖子。点击编辑器上方的Add Media按钮,并从唯一的下拉框中选择Uploaded to this post。如果这是空的,get_children将不会返回任何图像,而不管帖子的内容。

相关问题