WordPress 101: Adding a (YouTube) Meta Box to Page/Post Editing
Thursday, February 23rd, 2012  —  Comments

The current version of WordPress (WordPress 3.3.1) allows for a theme creator to implement a ‘Featured Image’ meta box on the page/post editor for use in a custom theme. This can easily be added by just adding a single line of code to the themes setup function.

But what if you want to add more meta boxes to your page/post editor. While not as easy as the one line above, it may be easier than you think.

A quick goggle search for “wordpress custom meta box” yields the following result.

http://codex.wordpress.org/Function_Reference/add_meta_box

The above reference page give a solid example on implementation. Check out my implementation below that allows you add a featured YouTube video to your post.

hooks

add_action( 'add_meta_boxes', 'featuredVideo_add_custom_box' );
add_action( 'save_post', 'featuredVideo_save_postdata' );

add meta box

function featuredVideo_add_custom_box() {
    add_meta_box(  'featuredVideo_sectionid', 'Featured Video', 'featuredVideo_inner_custom_box', 'post', 'side' );
}

print box

function featuredVideo_inner_custom_box( $post ) {
    wp_nonce_field( plugin_basename( __FILE__ ), 'featuredVideo_noncename' );
 
    // show featured video if it exists
    echo getFeaturedVideo( $post->ID, 260, 120);   
 
    echo '<h4 style="margin: 10px 0 0 0;">URL [YouTube Only]</h4>';
    echo '<input type="text" id="featuredVideoURL_field" name="featuredVideoURL_field" value="'.get_post_meta($post->ID, 'featuredVideoURL', true).'" style="width: 100%;" />';
}

handle box post

function featuredVideo_save_postdata( $post_id ) {
 
    // check autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
      return;
 
    // check authorizations
    if ( !wp_verify_nonce( $_POST['featuredVideo_noncename'], plugin_basename( __FILE__ ) ) )
      return;
 
    // update meta/custom field
    update_post_meta( $post_id, 'featuredVideoURL', $_POST['featuredVideoURL_field'] );
}

helper function, displays YouTube video, which can also be used to display the YouTube video within your theme

function getFeaturedVideo($post_id, $width = 680, $height = 360) {
    $featuredVideoURL = get_post_meta($post_id, 'featuredVideoURL', true);
 
    preg_match('%(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $featuredVideoURL, $youTubeMatch);
 
    if ($youTubeMatch[1])
        return '<iframe width="'.$width.'" height="'.$height.'" src="http://ww'.
               'w.youtube.com/embed/'.$youTubeMatch[1].'?rel=0&showinfo=0&cont'.
               'rols=0&autoplay=0&modestbranding=1" frameborder="0" allowfulls'.
               'creen ></iframe>';
    else
        return null;
}

and the final result

This entry was posted on Thursday, February 23rd, 2012 at 5:30 PM and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.
  • Maman Ashari

    Hi .. is this tutorial just to display the youtube on post editing?? 

    can i use it to display that video on my themes.. i try to put your last block  code to my forntpage but getting error message “****….Redeclare….***”..

    Pls help me with the code…

    Thanks…
    ps: sowry for my bad english

    • http://www.iamclarence.com Clarence Brown

      You can definitely use it in your theme. You would need to place the function in your post loop, passing it your post id and the height and width you want to display. 

      // show featured video if it exists
      echo getFeaturedVideo( $post->ID, 260, 120); And easy way to only show post  that has a video attached would be to add a special category for the post you have videos attached to.

  • Eddie

    Can i make the youtube thumbnail as my feauted image (post thumbnail) ?

    • http://www.iamclarence.com Clarence Brown

      You could probably do this, but I would advise against it. The YouTube preview image will often be very low-quality. YouTube images can be retrieved from the following URL: img.youtube.com/vi/VIDEOID/0.jpg.

      The getFeaturedVideo function can easily be altered to produce this URL.

      • TripsLeft

        I just changed the parameter in from “post” to my CPT in the function:function featuredVideo_add_custom_box()

  • suresh

    It is nice but when i update something its going null value to database and can’t play youtube. can u give me idea

  • Stole

    What about display Vimeo video ?

    • http://www.iamclarence.com Clarence Brown

      You would need to find a regular expression match to get the Vimeo video id from a URL, then re-configure the ‘getFeaturedVideo’ return value to Vimeo embed code.

  • TripsLeft

    Is there a way to only show this option on Custom Post Type editing screens?

    • http://www.iamclarence.com Clarence Brown

      This would probably need to be done w/ some type of JavaScript w/ .show() or .hide() based on post type selection and using and onchange event.

      I’ve done something like this for a client before based on which page template was selected, so I know it can be done.

    • TripsLeft

      disregard, I figured it out

  • TripsLeft

    How do you output the code in the theme, once the video url has been set?

    • http://www.iamclarence.com Clarence Brown

      Use the featuredVideo function, with your current loops post id.

      Something like…
      featuredVideo(post->ID, 1280, 720);

      • TripsLeft

        idk, that’s throwing an error, and when I change it to… featuredVideo($post->ID, 1280, 720);
        It breaks the site.

        • http://www.iamclarence.com Clarence Brown

          I’m not sure how proficient you are in WordPress/PHP. Did you put featuredVideo($post->ID, 1280, 720); within PHP tags?

          You may need to post the code somewhere or email me. Would say paste the code, but Disqus may strip the characters.

          • TripsLeft

            yes i did. I love this feature you’ve made. I just can’t get it working. I’ll keep playing around with it. If I figure it out, I’ll repost the solution. thanks for your suggestions though

          • TripsLeft

            I figured it out. I wasn’t echoing what your function was returning. SMH. Here’s the code in case anybody else needs it:

            $the_video_output = getFeaturedVideo($post->ID, 708, 366);

            echo $the_video_output;

            Thanks again, great function!