与此代码斗争,条件起作用,我获得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>
最合适的回答,由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\';
}