The right way to add custom field in wordpress post or page, add custom field and get custom field value, simple tutorial and example.

How To Add Custom Field In WordPress

Very easy, we need get_post_meta() function only, using get_post_meta() we will check if has custom field and get custom field value.

Add Custom Field

In this example we will add “youtube” custom field to embed youtube video in post using custom field.

In post or page editor click on “Screen Options” and checkbox “Custom Fields”:

show wordpress custom field options

Now in “Custom Fields” click on “Enter New”:

wordpress custom field

Now in “Name” field enter “youtube”, and in “value” field enter youtube video link, and click on “Add Custom Field” button:

add custom field

Get Custom Field Value

Now we will check if has “youtube” custom field, and get “youtube” custom field value, copy code and paste it anywhere you want:

global $post;
if( get_post_meta($post->ID, "youtube", true) ){ // Check if has youtube custom field
    $youtube_url = get_post_meta($post->ID, "youtube", true); // Get youtube custom field value
    $get_video_id = preg_replace("/(https?)?+(:\/\/?)?+(www.?)?+[a-zA-Z]+(.com|.be)+(\/)+(watch?)?+[(?)]?+(v=?|V=?)?|(&)+(.*)/", "", $youtube_url); // Get youtube video ID, Regex by Qassim Hassan
    echo '<iframe src="https://www.youtube.com/embed/'.$get_video_id.'"></iframe>'; // Display youtube video
}

Enjoy.

Tip: Read how to add custom post meta box in WordPress.