WordPress 101: Adding a (YouTube) Meta Box to Page/Post Editing

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