Blog for web designers

How to check custom fields exists or not

WordPress has a feature that allows us to add custom fields data into the post. By default the custom fields are disabled by wordpress. So you need to enable it first. To enable custom field, add a new post or edit any post if you have already made a post. You will see the Screen Option at the top right corner just behind the Help link. After that, check the Custom Fields under the “Show on screen”.

custom fields meta data

Add a custom field

Now lets just add a custom fields value to our post. After checking the custom fields checkbox, scroll down to the page to see the Custom Fields box. Write your first custom fields name under the Name. It will be a kind of variable to call in our template file. After that write a value you want to display in your post. It should be done under the Value tab.

Get custom fields value to our post

To get the custom fields value we do not need to add any function into the function.php file. Its quite easy to get it by the simple wordperss function.
Just copy the below code into your theme or where you want to display the value.


<?php echo get_post_meta($post->ID, 'Your Custom Fields Name', true);?>

Check if the custom fields exists or not

With the help of of some if else conditional statement we can check weather the our custom fields name has a value or not.

<?php
$key = 'sub-heading';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta != '') { ?>
<h2><?php echo get_post_meta($post->ID, 'sub-heading', true);?></h2>
<?php }?>

Santosh Shah

My name is Santosh Shah and blogs at santosh-shah.com


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.