我有一个CPT,可以通过滑块显示任何附加的图像。
但是,当没有附加图像时,滑块仍会显示。
有没有办法添加条件IF
语句,该语句将隐藏滑块或至少返回一些内联css,这些css将在容器上“显示:无”,并返回到下面的代码?这是cpt-single.php
页
<ul id="slider" class="exhibit-slide">
<?php $args = array(
\'post_type\' => \'attachment\',
\'orderby\' => \'menu_order\',
\'order\' => \'ASC\',
\'post_mime_type\' => \'image\',
\'post_status\' => null,
\'numberposts\' => null,
\'post_parent\' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$alt = get_post_meta( $attachment->ID, \'_wp_attachment_image_alt\', true );
$image_title = $attachment->post_title;
$caption = $attachment->post_excerpt;
$description = $attachment->post_content;
?>
<li>
<div class="exhibit">
<img src="<?php echo wp_get_attachment_url($attachment->ID); ?>" alt="<?php echo $alt; ?>">
</div>
</li>
<?php } } ?>
</ul>
最合适的回答,由SO网友:Howdy_McGee 整理而成
您需要在实际显示div之前添加查询,然后才能运行条件查询。根据get_posts()
它返回一个数组,所以我假设如果找不到帖子,它将返回一个空数组,因此我们可以检查它是否不是! empty()
<?php $args = array(
\'post_type\' => \'attachment\',
\'orderby\' => \'menu_order\',
\'order\' => \'ASC\',
\'post_mime_type\' => \'image\',
\'post_status\' => null,
\'numberposts\' => null,
\'post_parent\' => $post->ID
);
$attachments = get_posts( $args );
if( ! empty( $attachments ) ) :
?>
<ul id="slider" class="exhibit-slide">
<?php foreach ( $attachments as $attachment ) {
$alt = get_post_meta($attachment->ID, \'_wp_attachment_image_alt\', true);
$image_title = $attachment->post_title;
$caption = $attachment->post_excerpt;
$description = $attachment->post_content;
?>
<li>
<div class="exhibit">
<img src="<?php echo wp_get_attachment_url($attachment->ID); ?>" alt="<?php echo $alt; ?>">
</div>
</li>
<?php } ?>
</ul>
<?php endif; ?>