获得自定义帖子类型的第一张图片

时间:2013-04-12 18:58:02

标签: wordpress

我有这个自定义帖子类型图库。我想从帖子中打出第一张图片。

<?php 
$item_count = 1;
$args = array( 'post_type' => 'gallery', 'posts_per_page' => 10 );  
$loop = new WP_Query( $args ); 
$item_count = 1;
while ( $loop->have_posts() ) : $loop->the_post();  ?>
    <?php the_title();  ?>
    <div class="count"><?php echo $item_count; ?></div>
    <div class="thumbnail">
    // THE FIRST GALLERY ATTACHMENT IMAGE
    </div> 

<?php $item_count++; ?>
<?php endwhile; ?>

有什么想法吗?

注意:我在帖子上添加了Gallery没有简单的图片!

1 个答案:

答案 0 :(得分:1)

检查this WordPress Codex示例。

代码将显示与帖子相关联的第一张图片。

或者查看同时处理此问题的this WordPress论坛讨论。

<强>更新

转到外观&gt;编辑并选择主题功能(functions.php)。 在文件的末尾添加:

// Get URL of first image in a post
function catch_that_image($my_postid) {
global $post;


$first_img = '';
  ob_start();
  ob_end_clean();
            $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',  get_post_field('post_content', $my_postid), $matches);

$first_img = $matches [1] [0];

// no image found display default image instead
if(empty($first_img)){

$first_img = "/images/default.jpg";
}
return $first_img;
} ?>

现在在您的代码中修改代码的这一部分:

<div class="thumbnail">
   <?php echo catch_that_image($loop->ID) ?>
</div> 

UPDATE V2

我修改了代码以适合您的代码。

更新V3

我在我的开发网站上尝试了代码,然后我进一步修改了代码,直到代码按原样运行。你现在不应该有任何问题。