3
votes

I'm using wordpress CMS and CMB2 plugin for creating metaboxes and custom fields.So I'm trying to make on front end stuff like this:

IF my_custom_text_field have something inside(filled in) - then get this data, but if it is empty show some text. I'm using cmb2 custom metabox plugin to make custom metaboxes and fields. I have first part

    <?php $seo_title = get_post_meta( get_the_ID(), 'seo_general_title', true );  echo esc_html( $seo_title );?>

but how to get my custom text if this field is empty i don't know. there was topic with the same problem but it not works for me https://css-tricks.com/forums/topic/cmb2-display-group-field-meta-data-if-exists-if-empty-display-default-text/ Maybe someone can help? thanks.

2
please give more details such as the cms you are using ( i guess this is wordpress ) , take a look here minimal reproducible example to clarify your questionCharles-Antoine Fournel
updated, is it enough? I think it is like if statement for wordpress, but dont know how to detect if my cmb2 field is empty...nito

2 Answers

1
votes

This answer should help you :

https://wordpress.stackexchange.com/questions/56597/if-get-post-meta-is-empty-do-something

  <?php $seo_title = get_post_meta( get_the_ID(), 'seo_general_title', true ); 
  if ( !empty($seo_title)){
     echo $seo_title;
  }
 ?>
1
votes
<?php 
$seo_title = get_post_meta(get_the_ID(), 'seo_general_title', true);
$seo_title = (empty($seo_title)) ? "Default Value" : $seo_title;
echo $seo_title;

Or my preffered way since i think its readability is better (You define the value right in the IF clause, but be careful not to forget always put the assignment in the simple brackets)

<?php 
if (empty($seo_title = get_post_meta(get_the_ID(), 'seo_general_title', true)))
    $seo_title = "Default Value";
echo $seo_title;

Or the "most basic" way - but this expects that the get_post_meta() function always returns string value.

<?php
$seo_title = get_post_meta(get_the_ID(), 'seo_general_title', true);
if ($seo_title == "") {
    $seo_title = "Default Value";
}
echo $value;

In the end it really pretty much depends on your taste.