Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

How to make Custom Field in WordPress?

$
0
0

Overview

By reading the title the first question that arise in our mind is that “What is custom field?” The answer for this is: Custom field is the meta-data which means it is an arbitrary extra related information. Meta-data is the key-value pair. The key is the name which identifies the specific field and that remains same for each post and value is the information for each specific field which varies for each post.

How to create custom fields?

Custom fields are hidden by default if you want to make it visible click on “Screen Options” on the top right corner of the wp-admin then checkmark the custom field checkbox so that it will be visible at the bottom of the page.

Custom-field-1

Many themes or plugins use custom fields for achieving their functionalities. To create new custom field, add name and value in their respective fields and for already created custom field select the name from the drop down and then write value into value field.

Custom-field-2

For example here, I am creating two custom fields “Reading Time” and “Genre”.

Custom-field-3

How to display that custom fields into your page?

To display all the custom fields into your page you need to write:

<?php  the_meta(); ?>

Then the output generated will be as below:

<ul class="post-meta">
    <li><span class="post-meta-key">Reading Time:</span> 10 min</li>
    <li><span class="post-meta-key">Genre:</span> Motivation</li  >
    <li><span class="post-meta-key">slide_template:</span> default</li>
    <li><span class="post-meta-key">title-position:</span> default</li>
    <li><span class="post-meta-key">image-position:</span> default</li>
</ul>

Here first two are the custom fields that I have created and rest of three are theme default.

Custom-field-4

The problem with this method is that it will display all the custom fields and will not allow to display any specific custom field.

To display any specific custom field you need to write:

get_post_meta(int $post_di,string $key = ‘’,bool $single = false)

$key -> Name of the custom field that you want to display

In our example if we want to display only reading time and genre then write the below code:

<?php echo "<span>Reading Time:</span> ".get_post_meta($post->ID,'Reading Time','true'); ?>

<ul class="list-unstyled clearfix">
       <li class="pull-left"><?php echo "<span>Reading Time:</span> ".get_post_meta($post->ID,'Reading Time','true'); ?></li>
       <li class="pull-right"><?php echo "<span>Genre: </span>".get_post_meta($post->ID,'Genre','true'); ?></li>
</ul>

Custom-field-5

Conclusion

I hope that you have enjoyed reading the blog and it might help you in your upcoming project!! Have a great weekend.


Viewing all articles
Browse latest Browse all 595

Trending Articles