【问题标题】:use conditional tags / if / else on a custom function in Wordpress?在 Wordpress 中的自定义函数上使用条件标签 / if / else?
【发布时间】:2012-04-25 20:36:51
【问题描述】:

如果没有附件,如何隐藏img-tag?

(函数来自本教程:http://wp.tutsplus.com/tutorials/automagic-post-thumbnails-image-management/

<img src="<?php get_attachment_picture();?>" />

我需要这样的东西:

<?php if ( get_attachment_picture()) { ?>
<img src="<?php get_attachment_picture();?>">
<?php } else { ?>
show nothing, not even av default image
<?php } ?>

【问题讨论】:

    标签: wordpress function wordpress-theming thumbnails attachment


    【解决方案1】:

    您可以通过让函数返回缩略图而不是回显它来完成您需要的操作。

    从函数中删除这些行:

    else:
        $related_thumbnail = "images/default_thumbnail.jpg";  //define default thumbnail, you can use full url here.
    

    替换

    echo $related_thumbnail;
    

    return $related_thumbnail;
    

    你的代码就变成了

    <?php
    $attachment = get_attachment_picture();
    
    if ( ! empty($attachment) ) { ?>
        <img src="<?php echo $attachment; ?>">
    <?php } ?>
    

    我还没有测试过这些,所以我可能遗漏了一些东西,但这种方法应该有效。

    顺便说一句 - 我不明白为什么函数有这些行:

    ob_start();  
    ob_end_clean();  
    

    可能值得删除它们,

    【讨论】:

      【解决方案2】:

      如果您使用的是“标准”文章缩略图,则可以使用 has_post_thumbnail
      http://codex.wordpress.org/Function_Reference/has_post_thumbnail

      <?php 
      //This must be in one loop
      
      if(has_post_thumbnail()) {
          the_post_thumbnail();
      } else {
          // if there is no thumbnail, do nothing (or whatever you want) here
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 2012-01-31
        • 2011-12-09
        • 2019-02-01
        • 1970-01-01
        • 2020-12-29
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 2019-04-25
        相关资源
        最近更新 更多