Wordpress特色图片不显示

时间:2015-06-11 21:56:54

标签: php wordpress

我试图在我的主页(index.php)上显示一个小版本的精选图片作为帖子缩略图。为此我将它实现为div的背景图像。不幸的是,代码(以前一直在工作)已经停止工作,我找不到原因。我一直在寻找解决方案,但我无法弄明白。 我使用以下代码,但不幸的是它没有返回任何内容:

<?php $post_image_id = get_post_thumbnail_id($post_to_use->ID);
if ($post_image_id) {
$thumbnail = wp_get_attachment_image_src( $post_image_id, 'post-thumbnail', false);
if ($thumbnail) (string)$thumbnail = $thumbnail[0];
} ?>

<?php if (has_post_thumbnail()) : ?>
<div class="post_image_crop" style="background: url('<?php echo $thumbnail; ?>')">
</div>
<?php endif; ?>

您可以在此处查看:oliverprenzel.com

奇怪的是,我在我的single.php上做了完全相同的事情,它仍然有效。

<?php $post_image_id = get_post_thumbnail_id($post_to_use->ID);
if ($post_image_id) {
$thumbnail = wp_get_attachment_image_src( $post_image_id, 'post-thumbnail', false);
if ($thumbnail) (string)$thumbnail = $thumbnail[0];
} ?>

<?php if (has_post_thumbnail()) : ?>
<div class="post_image_bg" style="background: url('<?php echo $thumbnail; ?>'); background-size: 100% !important;">
</div>
<?php endif; ?>

您可以在这里查看:oliverprenzel.com/headmagazine/

有没有人知道可能导致这种情况的原因?

为Claudiu编辑: 这是我试图获取图像的循环:

<div class="wrapper">
<?php $post_image_id = get_post_thumbnail_id( $post_id );
    if ($post_image_id) {
        $thumbnail = wp_get_attachment_image_src( $post_image_id, 'post-thumbnail', false);
        if ($thumbnail) (string)$thumbnail = $thumbnail[0];
    } ?>
<!-- post loop prev -->
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<a href="<?php the_permalink() ?>">
    <div class="post_frame">
        <div class="post_image_crop" style="background: url('<?php echo $thumbnail; ?>')">
        </div>
        <div class="prev_det">
            <div class="prev_det_center">
                <h1>
                    <?php the_title(); ?>
                </h1>
                <p><?php echo get_the_category_list(', '); ?></p>
            </div>
        </div>
        <div class="prev_det_fold"></div>
    </div>
</a>
<?php endwhile; ?>
<?php else: ?>
<?php endif; ?>
</div>

2 个答案:

答案 0 :(得分:1)

我强烈怀疑你的第一行$post_to_use->ID返回null。当get_post_thumbnail_id()中的参数返回null时,默认情况下使用当前的post id。这就是为什么它在single.php中工作,因为你有一个帖子加载。

在首页上你不会。所以你必须检查你想要的帖子ID,手动输入或循环。

尝试将get_post_thumbnail_id($post_to_use->ID)替换为get_post_thumbnail_id(5),其中5是您想要的帖子ID。

答案 1 :(得分:1)

如果您想获得每个帖子缩略图,那么您需要移动

<?php $post_image_id = get_post_thumbnail_id( $post_id );
    if ($post_image_id) {
        $thumbnail = wp_get_attachment_image_src( $post_image_id, 'post-thumbnail', false);
        if ($thumbnail) (string)$thumbnail = $thumbnail[0];
    } ?>

在循环内部并将其更改为:

<?php $post_image_id = get_post_thumbnail_id( get_the_ID() );
    if ($post_image_id) {
        $thumbnail = wp_get_attachment_image_src( $post_image_id, 'post-thumbnail', false);
        if ($thumbnail) (string)$thumbnail = $thumbnail[0];
    } ?>

我的猜测是$post_image_id返回null,因为您的主页没有精选图片,即使您有,也会为每个帖子显示相同的图像。

相关问题