【问题标题】:Can I hide broken images?我可以隐藏损坏的图像吗?
【发布时间】:2010-08-23 16:01:29
【问题描述】:

我正在尝试创建一个侧边栏,我可以使用自定义字段在我的 wordpress cms 后端指定图像,现在我已经让它工作了,只有一个小错误,如果用户输入无效URL,图片链接会显示为损坏,不会显示,有没有办法可以隐藏损坏的图片图标?

我为父 DIV 元素设置了背景图像,这样如果没有图像要显示,父元素的背景就会显示。

这里是 PHP 代码:

//here I get the 'side_image' custom field, which will contain the URL to the side image    
if (have_posts()) : 
         while (have_posts()) : the_post(); 
             $side = get_post_meta($post->ID, 'side_image', true); 
         endwhile;
 endif;

HTML:

<!--here is the HTML markup-->
<div id="inner_content_right">
    <img src="<?php echo $side; ?>" />
</div>

CSS:

#inner_content_right {
    background: url(images/Layout_3_other_06_backup.jpg) no-repeat;
    width: 259px;
    height: 691px;
    float: right;
    position: relative;
    bottom: 28px;
}

提前谢谢!

【问题讨论】:

    标签: php html css wordpress


    【解决方案1】:

    你可以试试

    <!--here is the HTML markup-->
    <div id="inner_content_right">
        <img src="<?php if (@getimagesize($side)) echo $side; ?>" />
    </div>
    

    【讨论】:

    • @fabrik 我也没有。但是在这种情况下,整个问题是关于抑制错误情况,因此容错检查例程似乎是正确的。如果它坏了,图片就不会显示,而不是某种 gd 错误消息。至少对于博客的访问者来说是一个更愉快的体验:)
    【解决方案2】:

    谢谢伙计们,我可以使用这段代码了!

    //check if the string is a valid URL
    function checkURL($url)
    {
        return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
    }
    
    //returns a image with a valid URL or nothing at all
    function validateImage($one){
    if(!checkURL($one))
    {
        $errMsg .= "Please enter valid URL including http://";
        //return $errMsg;
    } else {
        $headers = get_headers($one, 1);
        $return = $headers[0];
        if($return!='HTTP/1.1 404 Not Found'){
            $string = "<img src='$one' />";
            return $string;
        }
        }
    }
    

    感谢您的帮助!

    【讨论】:

      猜你喜欢
      • 2013-07-29
      • 2022-11-07
      • 2019-05-06
      • 2017-06-26
      • 1970-01-01
      • 2018-01-29
      • 2017-06-16
      • 2018-10-04
      • 2019-03-13
      相关资源
      最近更新 更多