A standard WordPress post contains various amounts of data, such as the post title, categories, keyword tags and a featured image. But did you know that you can add a whole range of meta-data to each post that you can manipulate in any way you like using Custom Fields?

WordPress Custom Fields
Image Source: WerbeFabrik – Pixabay.com / License: CC0 Public Domain

What Are Custom Fields?

Custom Fields can be used to add additional pieces of information to any post, page, or even a custom post-type, which can be displayed via the Loop, such as within your index.php file.

Custom fields are stored using a Name/Value combination, each name can be assigned a value, and you can manipulate these values in multiple ways, just like you can using a database, but without the hassle of learning to master complex database queries.

Enabling Custom Fields

Since WordPress 3.1, custom fields have been tucked away behind the Screen Options tab at the top of the various Edit pages. Simply check the Custom Fields checkbox to enable the area, which will become visible directly below your post contents (by default).

Enable Custom Fields
Enabling Custom Fields in WordPress

This allows you to begin making use of this awesome, but very understated feature that truly does contribute to the argument that WordPress is one of the finest Content Management Systems (CMS) available today, currently powering around 26% of the internet.

A Simple Custom Field

Let’s create a really simple custom field in WordPress, assign a value to it and display it within our posts. Enter a name for your custom field in the Name field, and give it a value by entering some text within the Value field, like shown in this image:

WordPress Custom Fields

Click the Add Custom Field button once you are happy with your new custom field, complete the process by Publishing or Updating your post.

Displaying Custom Fields in WordPress

We now have a value assigned to a custom field in WordPress with the name of Overview, which we can display within our posts by adding this code within your theme’s loop:

the_meta();

This will create an unordered list of all custom fields that have a value assigned to it for the post currently being viewed. So if you had multiple custom fields that all had values assigned to them, they would all be displayed in a list. You can also display a single custom field using something more specific instead:

get_post_meta($post_id, $key, $single);

Let’s quickly explain the above code, $post_id is the ID of the post, to obtain the ID of the current post being viewed simply use $post->ID.

$key is the name you gave the custom field, in this example it is Overview, and $single accepts a boolean value of either true or false, if set to false (or if not set at all), the custom field will be returned as an array which is useful if you have multiple custom fields with the same key.

For this example, we will set $single as true, which will return a single value. The code for this example would look like this:

get_post_meta($post->ID, 'Overview', true);

Assign it to a variable (in this case $overview) so you can echo the contents of the chosen custom field, like so:

$overview = get_post_meta($post->ID, 'Overview', true);
echo $overview;

The possibilities are endless as you’re able to manipulate this extra data in many ways to create some very impressive results. Let us take a look at some cool things you’re now able to achieve.

Calculations

Perhaps you have multiple custom fields, each assigned a numeric value such as a price, and you need to add them together to achieve a Total figure. We can calculate the total figure using this sample code:

$total = get_post_meta($post->ID, 'price1', true);
$total += get_post_meta($post->ID, 'price2', true);
$total += get_post_meta($post->ID, 'price3', true);
$total += get_post_meta($post->ID, 'price4', true);

This assigns the value of the price1 custom field to the $total variable, and adds the values of the other price custom fields to the variable using the += operator. We can then output the total of these custom fields like so:

echo $total;

With this example in mind, you’re able to add cool features to your WordPress theme like a simple rating system for a review site, let’s take a look at how we could do that shall we?

Review Site Rating System

Perhaps you run a technology online magazine and want to add a simple rating system to your reviews, you can achieve this using just a few custom fields. Let’s start by adding 5 new custom fields to a post that we will be using to rate a product based on different criteria and assign a numeric value to each field out of 100, like so:

Rating System Custom Fields

We can now calculate an average of the above custom fields as seen in the following example:

$score = get_post_meta($post->ID, 'Affordability', true);
$score += get_post_meta($post->ID, 'Features', true);
$score += get_post_meta($post->ID, 'Reliability', true);
$score += get_post_meta($post->ID, 'Build Quality', true);
$score += get_post_meta($post->ID, 'Design', true);
$average = ($score) / 5;

Now we have an average of the 5 custom fields stored in the $average variable, which by default, may contain an unwanted decimal place. We can use basic PHP math functions to round-up or down the value before storing it within the $average variable, just replace the last line of the above code with your preferred choice of:

$average = ceil($score / 5); // rounded up
$average = floor($score / 5); // rounded down

Using the above sample values from the image, we should now have a value of either rounded 81 using the floor() function, or rounded 82 using the ceil() function, and without any math functions we’ll have a value of 81.2.

So how can we put all of this together?

Using a child theme of the TwentySixteen theme as an example, we can implement this simple rating system in no time at all and the outcome will look like this:

WordPress Custom Fields Rating System

Open your child theme functions.php file and add the following:

function review_ratings($content) {
    if (is_singular() && is_main_query()) {
        $content .= get_template_part('template-parts/content', 'ratings');
    }
    return $content;
}
add_filter('the_content', 'review_ratings');

This creates a new function that modifies the function that displays your post contents by inserting a file that contains our ratings code. The file we referenced above, using the get_template_part() function, needs to be created and put in the correct location.

Create an empty PHP file called content-ratings.php and put it in a newly created folder called template-parts. Now we can add the code responsible for displaying the ratings and average score values, copy and paste the code below into the content-ratings.php file we just created.

<?php
$score = get_post_meta($post->ID, 'Affordability', true); 
$score += get_post_meta($post->ID, 'Features', true); 
$score += get_post_meta($post->ID, 'Reliability', true); 
$score += get_post_meta($post->ID, 'Build Quality', true); 
$score += get_post_meta($post->ID, 'Design', true); 
$average = ceil($score / 5);
?> 

<div class="review-ratings"> 
    <div class="review-scores"> 
        <?php the_meta(); ?> 
    </div> 
    <div class="review-average"> 
        <h2 class="review-average-title"> 
            <?php echo $average; ?> 
        </h2> 
    </div> 
</div>

The above code makes the calculation we talked about earlier by adding all 5 custom fields together, and then dividing by 5 to obtain an average score, which is stored within the $average variable. Then we add a simple HTML structure that outputs our values, which enables us to use CSS to style the ratings in a way that matches the TwentySixteen theme’s existing style.

Simply add the following CSS code to your child themes’ style.css file:

.review-ratings { 
    border-color: inherit; 
    border-style: solid; 
    border-width: 1px 0 1px 0; 
    clear: both; 
    padding: 1.75em 0;
    margin-bottom: 1.75em; 
    overflow: hidden; 
    display: flex; 
    justify-content: center; 
    align-items: center; 
}
.review-scores, .review-average { 
    float: left; 
}
.review-scores { 
    width: 72.5%; 
}
.review-scores ul { 
    list-style-type: none; 
    margin: 0; 
}
.review-scores li { 
    background: #efefef; 
    margin-top: 3px; 
    padding: 0 5px; 
    text-align: right; 
}
.review-scores li:first-child { 
    margin-top: 0; 
}
.review-scores li span { 
    font-weight: 700; 
    font-style: italic; 
    float: left; 
}
.review-scores li::after, .review-average-title:after { 
    content: "\0025"; 
}
.review-average { 
    width: 25%; 
    margin-left: 2.5%; 
}
.entry-content .review-average-title { 
    font-size: 2.75rem; 
    text-align: center; 
    margin-bottom: 0; 
}

To Wrap It Up

We have used existing styles taken from the parent theme and percentage-based widths to ensure maximum compatibility between browser widths, and of course mobile devices. There we have it, with just a few lines of code we have implemented a simple rating system that looks good and adds additional functionality to your posts, just by making use of custom fields in WordPress.

ClickWhale - WordPress Link Manager