查询以显示Wordpress侧边栏/窗口小部件中最近发布的图片

时间:2010-04-11 19:51:27

标签: php wordpress

要在小部件中显示Wordpress类别中的最近项目,我正在使用此代码......

<ul>
<?php $recent = new WP_Query("cat=1231&showposts=5"); while($recent->have_posts()) : 
$recent->the_post();?>
<li><a href="<?php the_permalink() ?>" rel="bookmark">
<?php the_title(); ?>
</a></li>
<?php endwhile; ?>
</ul>

...但是如何让这个查询也显示每个帖子中的第一张图片,如果没有图片,有没有办法设置“默认”图片?

是否还有一种方法可以在这里使用缩略图,而不是加载完整尺寸的图像并使用HTML来调整大小?

1 个答案:

答案 0 :(得分:2)

这可能是您正在寻找的,找到here

function get_first_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)){ //Defines a default image
      $first_img = “/images/default.jpg”;
   }
   return $first_img;
}