如果未检测到缩略图,则显示附加媒体图像

时间:2014-08-18 08:12:38

标签: wordpress post sorl-thumbnail

我正在使用

 if ( has_post_thumbnail() ){}

检查帖子是否有缩略图, 但是这个

 echo get_attached_media('image', $post->ID);

显示单词

 Array

我需要显示附件图片

3 个答案:

答案 0 :(得分:1)

我发现了这个,并且它起作用

        <?php 
        if( has_post_thumbnail() )
        {
            // check if the post has a Post Thumbnail
           echo ' <a href="';
           the_permalink();
           echo '" title="';
           the_title_attribute();
           echo '">';
           the_post_thumbnail( 'medium' );
           echo '</a>';
        }
        else
        {
            $imgs = get_attached_media( 'image' );

            if( count( $imgs ) > 0 )
            {
                $img = array_shift( $imgs );
                echo wp_get_attachment_image( $img->ID, 'thumbnail' );
            }
        }
        ?>

对WPSE上的@birgire表示感谢和赞誉

答案 1 :(得分:1)

如果您尝试在帖子中只获取一张图片并将其用作缩略图,则可能需要尝试使用此图片:

将此添加到您的函数.php:

// Get URL of first image in a post
function catch_that_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];

// no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
}

要把它叫做

  

<?php echo catch_that_image() ?>

在循环中的模板文件中。

我从forum thread找到了这个精彩的代码。很多次救了我。

答案 2 :(得分:0)

您需要使用get_attached_media( 'image', $post->ID );

使用

echo get_attached_media( 'image' );

应该有用。

相关问题