Displaying WordPress Custom Fields

Displaying Custom Fields without Coding

This tutorial explains how to display custom fields using PHP and Types API functions.

You can also display custom fields without writing any code with Views plugin.

Types plugin allows you to easily create custom fields in your WordPress site. Once you’ve created these custom fields, you’re probably wondering how to display them. This tutorial shows just that.

The simplest ways to display custom fields, created by Types, are:

  1. With PHP coding and Types API functions
  2. Without any coding, using Views plugin

If you are fluent in PHP and feel at home around WordPress API, you’ll enjoy using Types PHP API. To display custom fields and build templates without writing any code, you should look at Views.

At the end of this tutorial, you’ll find two appendixes that explain how to load custom fields using the standard WordPress API, and even load custom fields directly from the database.

Although you don’t normally need to do this, these appendixes will add insights as to how WordPress stores custom fields in the database. Besides being interesting reading, it may help you gain better understanding of the underlying structure of your site.

1) Writing PHP code and using Types API to display custom fields

The easiest way to display custom fields, with just PHP, when you’re using Types plugin, is using Types fields API. A single API function called types_render_field will display all field types, using their correct output formatting.

Here is the function, with the different arguments it takes:

Types render field API basic structure
<?php

echo types_render_field("custom-field-slug-name", array("argument1"=>"value1","argument2"=>"value2","argument2"=>"value2"));

?>

custom-field-slug-name is the name of your custom field slug taken from the Types configuration such as this:

Custom field slug name

In the example above, the field slug is “coursename”. We will use the types_render_field call to display that field in the template.

Types plugin can create different kinds of custom fields. Types stores all of them in the database in the same way, but gives them different meanings. Field types include email, image, date, checkboxes and others. Each of these custom field types supports different arguments, that let you format it as you like. Read Types fields API to learn about the different options for different field types.

Example 1 – displaying formatted custom field values

To display the Trainer email, with the email-field formatting you can use the following code:

<?php

$trainer_email_address = types_render_field("email", array("output"=>"html"));

//Output the trainer email

printf("Trainer Email Address displayed using Types API: %s",$trainer_email_address);
?>

We’ve set the argument “output” to HTML to display the field as a mailto link. Types displays different custom fields with different formatting, based on their kind. See the full details about the email field in the email field documentation.

Note: The above code will automatically display all values of a repeating custom field.

Example 2 – displaying raw custom field values

If you want to display the custom field value as exactly as it is stored in the database (no formatting added by Types), you need to set raw=>true.

This is sometimes needed when you want to display things like image URLs without the <img> tags around them, or link destinations, without the <a> tags.

The following code displays all instances of the “email” field, separated by semicolons.

Setting Raw to TRUE in Types field API
<?php

$trainer_email_address = types_render_field("email", array("raw"=>"true","separator"=>";"));

//Output the trainer email

echo "Trainer Email Address displayed using Types API:".$trainer_email_address;
?>

We’ve added an additional “separator” parameter, with the value semicolon. This will separate the outputted email address by a semicolon. You can use any separator you like.

2) Displaying custom fields without coding using Views

Views plugin lets you display custom fields templates without writing any code.

You’ll be able to include custom fields in single pages or create you own content lists.

Views lets you create page templates right from within the WordPress GUI. You will design templates using regular HTML and CSS and insert fields into them.

Here is how it works:

I. Create Content Templates for your different content types

Inserting custom fields to templates via the WordPress GUI

II. Use Views dialog to insert any standard fields, custom fields or taxonomy

Inserting an image field into a template

III. Design template layouts using only HTML and CSS

Edit templates using HTML and CSS

Read more to learn how to build complete WordPress sites with Views without coding:


The End

The rest of this tutorial teaches the inner-working of WordPress custom fields.
Read on to learn how WordPress stores custom fields in the database and how to access them using low-level API calls.


Appendix A) Loading and Displaying Custom Fields Using WordPress API

The current WordPress API has lots of functions relating to custom fields. This makes it easier for developers to display custom field information.

One of the most important functions is get_post_meta(). Its function is to retrieve the custom field values of a particular post given its id and key.

To display custom field values correctly, it is important that you exactly know the meta_key used by your custom fields. Custom fields contain pairs of information:

  • meta_key – this is the custom field meta key name
  • meta_value -this is the custom field meta value

WordPress stores these values at the post meta table in your database. Below is an example of a WordPress post meta table showing the custom field meta key and values for different post_id. These custom fields are created by the Types plugin.

Custom field meta key and values in post meta table

The postmeta table includes four columns:

  • meta_id – the ID of the custom field
  • post_id – the post to which the custom field belongs
  • meta_key – the key (name) of the custom field
  • meta_value – the value stored in the custom field

Types plugin always appends a wpcf- prefix to meta keys. You should keep this in mind. As you have observed, the email custom field is stored as wpcf-email in the database.

Of course, in order to display the custom field’s value, you’ll need to know it’s meta_key. You can find out the meta_key for custom fields using several methods.

Checking custom field slugs in Types GUI

Types plugin appends wpcf- to the custom field slugs so the meta key stored in the WordPress database should start with wpcf (if created by Types). Below are the steps to determine the meta key used by your custom field without logging into a database:

  1. Login to your WordPress admin and go to Types->Custom Fields
  2. Select a custom field group
  3. Expand the field you’re looking for and check the ‘slug’ entry

The slug is the highlighted input

The slug in the GUI is “coursename”. So the meta key stored in the database by this custom field is wpcf-coursename.

Finding custom fields using the_meta() WordPress function

Put this code in your WordPress template that is using the custom fields (single.php for example):

The meta WordPress function
<?php 

the_meta();

?>

It will display results such as this:


wpcf-name: Mr Z
wpcf-email: z@yahoo.com, anothergreatemail@yahoo.com, anotheremail@yahoo.com

The meta key created by the Types plugin should start with wpcf. So they are:

  • wpcf-name
  • wpcf-email

Using the WordPress function get_post_custom_keys() to list custom fields

This will return all the meta key used by a specific ID. For example:

WordPress get_post_custom_keys
<?php
$meta_key_used=	get_post_custom_keys($post->ID); 
foreach ($meta_key_used as $meta_key) {
    echo $meta_key.'<br />';
}
?>

It returned results like:
_edit_last
_edit_lock
wpcf-name
wpcf-email
_views_template

Again, the Types custom fields’ meta key names should start with wpcf.

Once you know the meta key, it is now simple to retrieve and display the custom field value. Let’s look at some examples.

Basic Example – Displaying custom fields without any validation

Let’s say that you created a custom post type called “Trainers” using Types plugin. Then, you created the following custom fields for it:

  • Name -the name of the trainer (wpcf-name)
  • Email – the email address of the trainer (wpcf-email)

To display these custom fields using the standard WordPress API, we’ll use the get_post_meta function:

<?php echo "Trainer name: ".get_post_meta($post->ID,'wpcf-name',TRUE)?>
<br />

<?php echo "Trainer Email Address: ".get_post_meta($post->ID,'wpcf-email',TRUE)?>

Set the third parameter of get_post_meta to TRUE if you like to return only a single result, such as a string. Otherwise it will return an array.

Better Example – Display custom fields after checking that they exist

It is also very important to check if your custom fields are available and not empty before displaying them. The following code will display custom field values only if the fields exist:

Checking if custom field is empty
<?php 

//Check if custom field is empty
if (!((get_post_meta($post->ID, 'wpcf-email', TRUE))=='')) {

//Not empty

echo get_post_meta($post->ID,'wpcf-email',TRUE);

}
?>

A.1 Displaying Repeating Custom Fields using WordPress API

In reality, a single custom field can hold several values. These are called repeating custom fields. For example, a trainer might have several email addresses stored in a single email field.

In Types GUI, these are enabled by following the steps:

  1. In the WordPress admin, go to Types – Custom Fields.
  2. Click the Custom Field Group that you would like to edit.
  3. Scroll down in the fields and look under “Single or Repeating Field”.
  4. To enable this, make sure “Allow multiple instances of this field” is selected.

For example, see the screenshot below:

Allow multiple instances of this field

Types save them in the meta table to your database similar to saving a single value custom field. But they are identified uniquely in the meta table with different meta_id, for example:

Different meta id assignment for repeating custom fields

Example – Displaying all values of a custom field

If you like to display the entire meta values associated with a meta key (such as displaying all the email addresses of a certain trainer), then the following code will work:

Displaying repeating custom field values with get_post_meta
Trainers Email Addresses:<br />
<?php 
		
//Display all email address belonging to a trainer
		
$email_address_trainers=get_post_meta($post->ID,'wpcf-email');
         
foreach ($email_address_trainers as $email_address_trainer) {

     	echo $email_address_trainer.'<br />';

}      
	
?>

As you have observed, get_post_meta is not anymore set to TRUE because it is needed to retrieve all meta values of the custom field. The resulting variable is now an array and can be displayed using PHP foreach loops.

The above code will work fine also when the custom field only holds a single value.


Appendix B) Direct Database Access to WordPress Custom Fields

You can also use pure PHP methods to display custom field value of a specific post or id. This method requires some knowledge about SQL queries. The strategy is to connect to WordPress database and then query the equivalent meta value corresponding to your custom field meta key and post id.

For example, if you want to retrieve the email address of post_id=89. Then you want to query the WordPress post meta table such that the meta_key should be equal to wpcf-email and the post_id is equal to 89.To implement with PHP, let’s show some examples.

Example – Loading custom fields using get_var

If you are sure that you will only be retrieving one meta value corresponding to your meta key then use the $wpdb->get_var in executing your query, like this:

Retrieving a single custom field value with get_var
<?php 
//Declare $wpdb as global, this will allow you to access the WordPress database.
global $wpdb;

//Define the WordPress post meta table

$metatable = $wpdb->prefix."postmeta";

//Retrieve post_id of every trainer page
$post_id_trainer=$post->ID;

//Formulate the SQL query
//Using prepared statements is the correct method
//You should be using this for security reasons

//Use $wpdb->get_var for retrieving single result
 
$trainer_emails = $wpdb->get_var($wpdb->prepare("SELECT meta_value FROM $metatable where post_id=%d AND meta_key='wpcf-email'",$post_id_trainer));

//Output the email address to your theme
//Simple echo the variable directly containing the result query
 
echo $trainer_emails;

?>

Use %d in the placeholder if you are passing integers in your query. In addition, use %s placeholder if the variable in the query is a string. If your custom field key contains several meta values, then only one of them will be returned if you are using the above code.

Read this WordPress article on $wpdb global variable for more information about formulating queries correctly.

B.1) Displaying Repeating Custom Fields using raw PHP

Let’s display the trainer email address of every trainer page. Take note that there are trainers with several email addresses. Below is the sample code:

Retrieving repeating custom field values with get_results
<?php 
global $wpdb;

$metatable = $wpdb->prefix."postmeta";

$post_id_trainer=$post->ID;

$trainer_emails = $wpdb->get_results($wpdb->prepare("SELECT meta_value FROM $metatable where post_id=%d AND meta_key='wpcf-email'",$post_id_trainer));

//Output the email address in your theme template
 
foreach ($trainer_emails as $trainer_email) {

	echo $trainer_email->meta_value.'<br />';

}

?>

As you can see the variable $trainer_emails will be an array since there are trainers with several email addresses, and the above code will display them correctly using foreach loops.