M
M
MrSusua2016-03-16 19:16:40
WordPress
MrSusua, 2016-03-16 19:16:40

How to check if there is data in a field?

Good afternoon!
How to check if a field is empty in a function:

<?php echo get_post_meta($post->ID, 'value', true);  ?>

And if not empty, then output it, otherwise not.
Something like:
if isset ($value) {
<p>
<?php echo get_post_meta($post->ID, 'value', true);  ?>
</p>
}

What is it for? So that an empty paragraph or container does not hang out in the code.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kernUSR, 2016-03-16
@kernUSR

I understand that you need to check what the get_post_meta() function returns?
if so, then check
But this will only work when the get_post_meta() function returns NULL or FALSE. If it can return a space, then it's better to check the length of the string.

I
Igor Vorotnev, 2016-03-16
@HeadOnFire

If the field exists and the value is not empty:

if( ! empty( get_post_meta( $post->ID, 'value', true ) ) ) {
    echo get_post_meta($post->ID, 'value', true);
}

If you need to check for a space (mentioned kernUSR edge case), then you can wrap it in trim:
if( ! empty( trim( get_post_meta( $post->ID, 'value', true ) ) ) ) {
    echo get_post_meta($post->ID, 'value', true);
}

But, IMHO, it's overkill. It is unlikely that you will have fields with spaces, although if it is user generated content, then everything is possible.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question