Search
Close this search box.

WordPress Custom Fields – Adding Custom Meta Data To Posts

[updated_on]
Share this post:

WordPress custom fields are one of the reasons the platform is so popular. Once you master them, you can create literally any kind of website you want. You can even create each section of your site to be completely different than the others. The basis is what I’m going to show you in this tutorial.

You can either watch the detailed video tutorial below or scroll below that to read the image/text version of the tutorial.

Output A Single Custom Field

<?php
  // set the variable to the value entered for the "Weather" custom field
  $weather = get_post_meta($post->ID, 'Weather', true);
  // check if the weather variable has a value
  if($weather){ ?>
     <!-- if the weather variable has a value and echo out this sentence in addition to the value of the variable -->
     <p>Weather when I wrote this: <?php echo $weather; ?></p>
  };
 <?php 
  // if the weather variable does not have a value then do the following
  }else{ 
    // do nothing
  }
 ?>

Output Multiple Custom Fields As A List

<?php
  $cost = get_post_meta($post--->ID, 'Cost', true);
  $friendliness = get_post_meta($post-&gt;ID, 'Friendliness', true);
  $cleanliness = get_post_meta($post-&gt;ID, 'Cleanliness', true);
  // check to make sure at least one of the custom fields have a value
  if($cost || $friendliness || $cleanliness ){ ?>
<ul class="important-details"><?php
    // output Cost if it is added as a custom field
    if($cost){ ?>
<li>Cost: <?php echo $cost; ?></li>
<?php 
      }else{ 
        // do nothing
      }
    // output Friendliness if it is added as a custom field
    if($friendliness){ ?>
<li>Friendliness: <? echo $friendliness; ?></li>
<?php 
      }else{ 
        // do nothing
        }
    // output Friendliness if it is added as a custom field
    if($cleanliness){ ?>
<li>Cleanliness: <? echo $cleanliness; ?></li>
<?php 
      }else{ 
        // do nothing
      }
     ?></ul>
<?php }?>

CSS From The Video Tutorial

.important-details {
  margin-bottom: 10px;
  background-color: #fff;
  content: "";
  display: table;
  clear: both;
  padding: 10px;	
}

.important-details li {
  float: left;
  list-style: none;
  margin-right: 20px;
}
Share this post:

4 thoughts on “WordPress Custom Fields – Adding Custom Meta Data To Posts”

  1. sir i added a custom field phone number and i dont know how to check existance of the phone number from already created users could you help me

    1. Hi Nani,

      In the PHP output on the page you can use PHP “if statement” to check if the phone number field has a value. On that blog post I’ve used a similar if statement to see if there is a value for “Weather”. It’s the very first code box on the post.

      Does that help?

Leave a Comment

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

WPLearningLab