回声混合的PHP和HTML - 语法

时间:2012-07-12 23:23:55

标签: php

我正在尝试显示一个缩略图,如果它存在于div类中,但是它以意想不到的方式输出代码(比如固定链接在href之外)

我在做错了什么?

<?php
 if (has_post_thumbnail( $post->ID ) ) {
   $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
   echo '<div class="thumbnail"><a href="' . the_permalink() . '">' . $image[0] . '</a></div>';
 } else {
   echo '';
 }
?>

结果

 http://www.permalink.com/<div class="thumbnail"><a href="">http://www.mysite.com/wp_myblog/wp-content/uploads/2011/10/fretless-thumbnail1.jpg</a></div>

并且不,我没有遗漏任何胡萝卜,括号,引号或任何其他代码。这是复制和过去究竟是如何输出

编辑:修正

我不得不添加一些额外的HTML,因为修复只会吐出jpg url sans img标签。此外,它没有显示正确的图像 - 它显示原始的jpg而不是缩略图版本

<?php
    if (has_post_thumbnail( $post->ID ) ) {
        $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
        echo '<div class="thumbnail"><a href="' . get_permalink() . '">' . '<img src="' . $image[0] . '"></a></div>';
    }
?>

YAY!

1 个答案:

答案 0 :(得分:3)

the_permalink函数已包含echo语句。

将其更改为get_permalink,它应该可以正常运行:

<?php
    if (has_post_thumbnail( $post->ID ) ) {
        $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
        echo '<div class="thumbnail"><a href="' . get_permalink() . '">' . $image[0] . '</a></div>';
    }
?>

你也不需要else位。这可能是多余的。

事实上,对于一个稍微更整洁的替代方案,这可能会起作用(从我自己的代码修改;只是添加了链接):

<?php if ( has_post_thumbnail() ) : ?>
    <div class="hover_img">
        <a href="<?php the_permalink(); ?>">
            <?php the_post_thumbnail('thumbnail'); ?>
        </a>
    </div>
<?php endif; ?>