如果查询没有帖子,则隐藏文本

时间:2015-07-27 作者:Kevin Mamaqi

我使用自定义查询在另一个CPT中显示事件CPT。给定的查询有一个节标题,当没有事件时,我不知道如何隐藏它。

enter image description here

我试着在代码中包含章节标题:

<!-- EVENTOS -->
<div class="container">
    <div class="row">
        <!-- Section title I want to hide when no posts found -->
        <div class="col-sm-12"><h2 class="seccion">Tour</h2></div>
        <?php
        $today = current_time(\'Ymd\');

        $args = array(
            \'post_type\' => \'evento\',
            \'post_status\' => \'publish\',
            \'numberposts\' => \'4\',
            \'meta_query\' => array(
                \'relation\' => \'AND\',
                array(
                    \'key\' => \'artista_del_evento\', 
                    \'value\' => \'"\' . get_the_ID() . \'"\',
                    \'compare\' => \'LIKE\'
                    ),
                array(
                    \'key\' => \'fecha_del_evento\',
                    \'compare\' => \'>=\',
                    \'value\' => $today,
                    )
                ),
            \'meta_key\' => \'fecha_del_evento\',
            \'orderby\' => \'meta_value\',
            \'order\' => \'ASC\',
            );

        $query = new WP_Query($args);
        if ($query->have_posts()) :
            while ($query->have_posts()) : $query->the_post(); 
        ?>

        <div class="col-sm-3">

            <?php 
            if(get_field(\'fecha_del_evento\'))
            {
                $datetime = DateTime::createFromFormat(\'Ymd\', get_field(\'fecha_del_evento\'));
                $fecha_dia = $datetime->format(\'d\');
                $fecha_mes = $datetime->format(\'M\');
            }            
            ?>
            <div class="eventos row">
                <div class="col-xs-3">
                    <div class="fecha">
                        <p class="mes"><?php echo $fecha_mes; ?></p>
                        <p class="dia"><?php echo $fecha_dia; ?></p>
                    </div>
                </div>
                <div class="col-xs-9">
                    <?php the_content (); ?>
                </div>
            </div>
        </div>


    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>

<?php endif; ?>

</div><!-- #row -->
</div><!-- #container -->

1 个回复
最合适的回答,由SO网友:Mayeenul Islam 整理而成

删除第#5行并执行以下操作:

if ($query->have_posts()) :
echo \'<h2 class="seccion col-sm-12">Tour</h2>\'; //we are showing the div inside the conditional
我删除了不必要的<div>, 像<h2> 它本身是一个块元素,可以为您实现这个技巧。

结束