如果存在数据,则仅显示按钮

时间:2018-02-23 11:00:35

标签: php wordpress if-statement is-empty

我在WordPress中使用了这段PHP代码,现在它显示了UK和DK两个按钮,即使其中一个只有数据。 DK的数据使用此字段名称“streaming_from_shop”,英国使用此“streaming_from_shop_uk”。 如何让它只显示在字段中写入数据的按钮而不显示另一个?当然,还要显示两个字段中是否存在数据。

<?php
    $streaming_link = get_field('streaming_from_shop');
    if( $streaming_link ):
?>
<?php
setup_postdata($streaming_link);
?>
<a href="<?php the_field('streaming_from_shop'); ?>" class="buttonstream_shop" target="_blank">Stream DK</a>
<a href="<?php the_field('streaming_from_shop_uk'); ?>" class="buttonstream_shop" target="_blank">Stream UK</a>
<?php wp_reset_postdata(); ?>
<?php endif; ?>

2 个答案:

答案 0 :(得分:1)

似乎您正在使用高级自定义字段。 ACF具有检查字段是否存在的功能。 https://www.advancedcustomfields.com/resources/the_field/因此,如果该字段存在,请检查它。

<?php if( get_field('streaming_from_shop') ): ?>
    <a href="<?php the_field('streaming_from_shop'); ?>" class="buttonstream_shop" target="_blank">Stream DK</a>
<?php endif; ?>

<?php if( get_field('streaming_from_shop_uk') ): ?>
    <a href="<?php the_field('streaming_from_shop_uk'); ?>" class="buttonstream_shop" target="_blank">Stream UK</a>
<?php endif; ?>

答案 1 :(得分:1)

试试这个:

<?php if (!empty(the_field('streaming_from_shop'))) { ?>
    <a href="<?php the_field('streaming_from_shop'); ?>" class="buttonstream_shop" target="_blank">Stream DK</a>
<?php } ?>
<?php if (!empty(the_field('streaming_from_shop_uk'))) { ?>
    <a href="<?php the_field('streaming_from_shop_uk'); ?>" class="buttonstream_shop" target="_blank">Stream UK</a>
<?php } ?>