When working with custom fields in WordPress, it’s necessary to know how to actually display those values on the page. And much of the time, you may have markup associated with that custom field that you only want displayed if the field actually has a value. We are going to learn how to do just that.
In this example, we have a custom field named “website” and we want it displayed as a link on the page, but only if it has a value, to prevent having a link element with no URL. We are going to be using “get_post_meta”, because this is the easiest way to get to our custom fields and values, which are considered part of the meta of a post.
The Code:
1 2 3 |
$meta_value = get_post_meta( $post->ID, 'website', true ); if (!empty( $meta_value )) {echo '<a href="' . $meta_value . '">The Website Link</a>';} else {} ?> |
Here is what the code is actually doing. First, we get the value of our custom field and assign it to a variable, $meta_value. Then we say, if it’s not empty, then parse our link markup, using the value as the link target. In this example, the value would be a URL. If our value IS empty, then display nothing.
And so we can easily display our value and markup only if it has a value, otherwise do nothing. This code should work fine with custom post types as well, which is where I get the most use out of it. Combine this method of displaying custom fields and meta values with the flexibility of custom post types for truly powerful, custom WordPress sites.
Check out this method of custom field use to make the whole process a piece of cake.
One Comment on “How to Display Custom Field Value Only If it Has Value”
Seu fragmento de código foi o único que resolveu o meu problema. Muito obrigada!