questions

If metabox is empty display other content in WP

Rate this post

I’m trying to replace or show other content if the metabox is empty but I can’t make it work, here is what I have done.

If “ytvideourl” is empty display “ytembed” iframe content

<div class="trailer"><iframe src="<?php echo get_post_meta($post->ID, 'ytvideourl', true);?>

<?php if( ! empty( $ytvideourl ) ) : ?>

 <iframe src="https://www.youtube.com/embed/<?php echo get_post_meta($post->ID, 'ytembed', true);?>?rel=0"><?php endif; ?> ?rel=0"></iframe></div>

Real current code:

<div class="trailer"><?php
    $ytvideourl = get_post_meta($post->ID, 'ytvideourl', true);
?>
    
    <?php if( ! empty( $ytvideourl ) ) : ?><iframe src="<?php echo $ytvideourl; ?>"></iframe><?php else : ?><iframe src="https://www.youtube.com/embed/<?php echo get_post_meta($post->ID, 'ytembed', true);?>?rel=0?" width="400" height="230" frameborder="0" allowfullscreen="allowfullscreen"><span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span><span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span><span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span><span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span></iframe><?php endif; ?></div>

 

✔️Solution:

First, you have to store the meta value to a variable. Then check whether that variable is empty or not. If not empty, then use that value. Otherwise if it’s empty, then fetch the second meta value and use it.

Here’s the example:

<?php
    $ytvideourl = get_post_meta($post->ID, 'ytvideourl', true);
    if( $ytvideourl !== false ) $ytvideourl = trim( $ytvideourl ); //-- remove any white spaces
?>
<div class="trailer">
    <?php if( ! empty( $ytvideourl ) ) : ?>
        <iframe src="<?php echo $ytvideourl; ?>"></iframe>
    <?php else : ?>
        <iframe src="https://www.youtube.com/embed/<?php echo get_post_meta($post->ID, 'ytembed', true);?>?rel=0"></iframe>  
    <?php endif; ?>
</div>

Leave a Reply

Your email address will not be published.

Back to top button