By default, WordPress provides 2 options to add data (title and description). If we need more fields we need to customize it or use hooks. In this article, we will learn how to make custom fields in WordPress options.
WordPress default fields options
The default fields provided by WordPress are:
- The title (text field)
- The description (text editor)
If we want to add more data on the page or post template, we have to customize it. We can either use the Advanced Custom Fields plugin or use Custom Fields provided by WordPress options.
We can enable custom fields option using Screen Options as below:
Once you enable it, you will see following section will appear. (You need to scroll down to see it because this is added below the main text editor)
Click on the “Enter New” to create your own field or you can select 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 WordPress post or page template, you need to add the following snippet in the content loop:
<?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 custom field, the output will be
Please note that you have to write the snippet to fetch the custom field’s values in the loop of your template where it is fetching the content of the post or page.
See how to use Advanced Custom Fields plugin.