By default, WordPress provides 2 options to add data (title and description). If we need more fields we need to customize them or use hooks. In this article, we will learn how to create custom fields in WordPress posts or page template
WordPress default Custom fields options
The default fields provided by WordPress are:
- The title (text field)
- The description (text editor)
If we want to add more data to the page or post template, we have to customize it. We can either use the Advanced Custom Fields plugin or use Custom fields in WordPress posts or page templates, provided by WordPress built-in options.
We can enable the custom fields option using Screen Options.
Click on the top right 3 dots (1) and click on the Preferences (2) (see below) :
This will open a window. Now click on Panels (3) and then enable the Custom Fields (4) option under the additional section (see below) :
Once you enable it, you will see the following section will appear (you need to scroll down to see it because this is added below the main text editor)
Click on the “Add Custom Field” to create your own field or you can select it from the dropdown. The “Value” will contains the value that you want to display on your page or post.
To display the value of custom fields in a WordPress post or page template, you need to add the following snippet in the content loop of the template file:
<?php $my_custom_data = get_post_meta( get_the_ID(), 'my_custom_data', true); ?>
Here, the parameter “my_custom_data” is the name of your custom field which you will add in the post. In the above snippet, we are assigning data in a variable. You can manipulate data as per your needs e.g. in the following snippet we have manipulated the value of custom fields in WordPress post:
<?php $w_phone = get_post_meta( get_the_ID(), 'w3_phone', true); $w_phone = str_replace(" ","",$w_phone); $w_phone = str_replace("(","",$w_phone); $w_phone = str_replace(")","",$w_phone); $w_phone = str_replace("-","",$w_phone); ?> <a href="tel:<?php echo $w_phone; ?>">Phone</a>
In this example, we have created a custom field “w3_phone” and cleaned the phone number by omitting parentheses and spaces e.g. if we write
+1 (234) 156 7890 in the value of the custom field, the output will be
You have to write the snippet to fetch the custom field’s value in the loop of the WordPress template where it is fetching the content of the post or page.