2012-07-12 67 views
0

我想要得到的缩略图显示,如果一个div类中存在,但它以意想不到的方式输出代码(如固定链接是在href之外)PHP和HTML的回声混合 - synatx

我究竟做错了什么?

<?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> 

也没有,我没有留下任何胡萝卜,括号,引号或任何其他代码。这是复制和过去,它究竟是如何outputing

编辑:FIX

我不得不添加一些额外的HTML,因为修复程序只吐出JPG网址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!

+3

有什么结果的HTML? – zerkms 2012-07-12 23:25:38

+0

服务器是否知道它是一个PHP文档?编辑为 – Rimian 2012-07-12 23:28:18

+0

以包含输出。是的,这是一个有效的PHP文件。 – 2012-07-12 23:29:50

回答

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; ?> 
+0

啊!我知道这将是这样简单的事情。谢谢!但这会导致您可能能够回答的另一个问题。它不会输出正确的图像。即使我将精选图像设置为缩略图,页面也会显示完整大小的图像。这是另一个备用电话问题吗? – 2012-07-12 23:40:18

+0

nm,想通了 – 2012-07-12 23:51:25

+0

我已经添加了一个更清洁的解决方案@kristinachilds :) – dunc 2012-07-13 00:03:05