You can add Custom Fields to your templates in several ways to display the output of the fields you’ve set. The easiest way involves using the get_post_meta();
template tag function, which looks like this:
<?php $key="<em>NAME</em>"; echo get_post_meta($post->ID, $key, true); ?>
Here’s how that function breaks down:
<?php
: Starts the PHP function. Every template tag or function needs to start PHP with<?php
.$key="<em>NAME</em>
";: Defines the name of the key that you want to appear. You define the name when you add the Custom Field to your post.echo get_post_meta:
Grabs the Custom Field data and displays it on your site. In this example this call for post meta has three parameters:- (
$post->ID
: A parameter that dynamically defines the specific ID of the post being displayed so that WordPress knows which metadata to display. $key,
: A parameter that gets the value of the Custom Field based on the name, as defined in the$key="<em>NAME</em>
"; setting earlier in the code string.true);
: A parameter that tells WordPress to return a single result rather than multiple results. (By default, this parameter is set totrue
; don’t change it unless you’re using multiple definitions in the Value setting of your Custom Field.)
- (
?>
: Ends the PHP function.
$key="mood";
part of the function tells WordPress to return the value for the Custom Field with the Name of mood
.