从媒体库中获取图像。纠结于代码吗?

时间:2011-03-05 作者:erichmond

与此代码斗争,条件起作用,我获得wp\\u get\\u attachment\\u url的唯一方法是循环使用它,但这样会从媒体库输出尽可能多的图像,而我只想要一个?

  <div class="tvimage">
  <?php
    if ($imgurlbase != \'\' ) { ?>

    <img src="<?php bloginfo(\'template_url\'); ?>/timthumb.php?src=<?php echo $imgurlbase . $imgfromtv; ?>&h=62&w=75" alt="<?php echo $programme; ?>">

            <?php } elseif ($imgurlbase == \'\' ) { ?>

            <?php
    $args = array(
        \'post_type\' => \'attachment\',
        \'numberposts\' => -1,
        \'post_status\' => null,
        \'post_parent\' => null,
        ); 
    $attachments = get_posts( $args );


                foreach ( $attachments as $attachment ) {

                    if ($attachment->post_title == $programme) {
                            echo wp_get_attachment_url($attachment->ID);
                        }
                    else {
                    echo \'<img src="\';
                    echo bloginfo(\'template_url\');
                    echo \'/images/nontvimg.jpg" alt="no tv image" />\';
                    }

                }


    ?>



            <?php } ?>


</div>

2 个回复
最合适的回答,由SO网友:Boone Gorges 整理而成

如果要在找到附件后退出循环,请使用break.

 // Define $programme and pull up $attachments as above
 $attachment_url = \'\';
 foreach ( $attachments as $attachment ) {
     if ($attachment->post_title == $programme) {
         $attachment_url = wp_get_attachment_url($attachment->ID);
         break;
     }
 }

 if ( $attachment_url ) {
     echo $attachment_url;
 } else {
     echo \'/images/nontvimg.jpg\';
 }

SO网友:erichmond

排序这是新代码:

<?php
            if ($imgurlbase != \'\' ) { ?>

            <img src="<?php bloginfo(\'template_url\'); ?>/timthumb.php?src=<?php echo $imgurlbase . $imgfromtv; ?>&h=62&w=75" alt="<?php echo $programme; ?>">

            <?php } elseif ($imgurlbase == \'\' ) { ?>

                <img src="<?php bloginfo(\'template_url\'); ?>/timthumb.php?src=<?php
                $args = array(
                    \'post_type\' => \'attachment\',
                    \'numberposts\' => -1,
                    \'post_title\' => $programme
                    ); 
                $attachments = get_posts( $args );

                $found = 0;
                foreach ( $attachments as $attachment ) {
                   if ($attachment->post_title == $programme) {
                      echo wp_get_attachment_url($attachment->ID);
                      ++$found;
                   }
                }
                if (!$found) {
                   echo \'/images/nontvimg.jpg\';
                }

                ?>&h=62&w=75">


            <?php } ?>

结束

相关推荐

Resizing all images

我刚刚更改了博客的主题,由于页面宽度很小,它打破了布局。我之前的大多数图片(附在帖子中)的宽度都在600px左右,现在我需要按450px的比例调整它们的大小。如何一次性调整它们的大小?有这个插件吗?P、 美国:编写CSS规则是一个很好的选择,我已经做到了。但我认为调整图像大小也会减少每个页面的下载开销!