Why my string variable recognized as empty?

I have an input with PHP Theme editor for Wordpress, and save it to some variable.

I want to render (echo) out the variable if is not an empty variable.

If I don't use If, it'll work okay (it is proof the variable not empty)

<div class="role"><?php echo get_post_meta( get_the_ID(), 'hcf_single_role_1', true );?></div>

But when I want to echo the only variable with value, it works otherwise

<?php if(!empty($post_id['hcf_single_role_1'])) { ?> //if not empty
   <div class="name"><?php echo get_post_meta( get_the_ID(), 'hcf_single_role_1', true );?></div>
<?php } else { ?> //if empty
   Variable Empty
<?php } ?>

if I change to if(empty()) it'll just work otherwise, my variable recognized as an empty variable.

*edit: I also tried if(!empty($_POST['hcf_single_role_1'])), but it's the same

1 answer

  • answered 2021-06-19 06:53 louislugas

    Based on @ChrisHaas comment, I tried this method, and it works

    <?php if(!empty(get_post_meta( get_the_ID(), 'hcf_single_role_1', true ))) { ?> //if not empty
       <div class="name"><?php echo get_post_meta( get_the_ID(), 'hcf_single_role_1', true );?></div>
    <?php } else { ?> //if empty
       Variable Empty
    <?php } ?>
    

    The method before I messed up between array and string variables.

    So I clean up with the same method I echoed with get_post_meta() as the if condition