Skip to Content

How to Add Responsive Featured Video for WordPress Posts Without a Plugin

|WordPress|0 Comments

This article will show you how to add an optional featured video to replace your WordPress post featured image. Hope to help those looking for a way to freely create responsive video blogs in a plugin or theme without worrying about installing unfamiliar plugins. It’s also intended for people that know their way around the basics of creating WordPress plugins and how themes work.

Most of the code here is based off of: Creating a Shortcode for Responsive Video (showing how to create a full plugin) from tuts+ and Fluid Width Video from CSS-Tricks.

 

Add the Meta Box

First, add a meta box in your theme or plugin. If you don’t already have something in place for that, here’s the code to do it:

<?php

// Add the Page Meta Box
function onepix_add_custom_meta_box() {
    add_meta_box(
            'onepix_meta_box', // $id
            '1 Pixel Page Options', // $title 
            'onepix_show_custom_meta_box', // $callback
            'page', // $page
            'normal', // $context
            'high'); // $priority
}

add_action('add_meta_boxes', 'onepix_add_custom_meta_box');

// Add the Post Meta Box
function onepix_add_custom_post_meta_box() {
    add_meta_box(
            'onepix_meta_box', // $id
            '1 Pixel Page Options', // $title 
            'onepix_show_custom_post_meta_box', // $callback
            'post', // $post
            'normal', // $context
            'high'); // $priority
}

add_action('add_meta_boxes', 'onepix_add_custom_post_meta_box');

$prefix = 'onepix_';

// Field Array (Pages Meta)
$onepix_meta_fields = array(
//	array(
//		'label'=> 'Text Input',
//		'desc'	=> 'A description for the field.',
//		'id'	=> $prefix.'text',
//		'type'	=> 'text'
//	),
//	array(
//		'label'=> 'Textarea',
//		'desc'	=> 'A description for the field.',
//		'id'	=> $prefix.'textarea',
//		'type'	=> 'textarea'
//	),
//	array(
//		'label'=> 'Checkbox Input',
//		'desc'	=> 'A description for the field.',
//		'id'	=> $prefix.'checkbox',
//		'type'	=> 'checkbox'
//	),
//	array(
//		'label'=> 'Select Box',
//		'desc'	=> 'A description for the field.',
//		'id'	=> $prefix.'select',
//		'type'	=> 'select',
//		'options' => array (
//			'one' => array (
//				'label' => 'Option One',
//				'value'	=> 'one'
//			),
//			'two' => array (
//				'label' => 'Option Two',
//				'value'	=> 'two'
//			),
//			'three' => array (
//				'label' => 'Option Three',
//				'value'	=> 'three'
//			)
//		)
//	)
);

// Field Array (Posts Meta)
$onepix_post_meta_fields = array(
    array(
        'label' => 'Featured Video Embed Code',
        'desc' => 'Paste your video code here to show a video instead of a featured image.',
        'id' => $prefix . 'video_embed',
        'type' => 'textarea'
    )
);

// The Callback for page meta box
function onepix_show_custom_meta_box() {
    global $onepix_meta_fields;
    onepix_show_page_meta_box($onepix_meta_fields);
}

// The Callback for post meta box
function onepix_show_custom_post_meta_box() {
    global $onepix_post_meta_fields;
    onepix_show_page_meta_box($onepix_post_meta_fields);
}

// The Callback
function onepix_show_page_meta_box($meta_fields) {

    global $post;
// Use nonce for verification
    echo '<input type="hidden" name="custom_meta_box_nonce" value="' . wp_create_nonce(basename(__FILE__)) . '" />';

    // Begin the field table and loop
    echo '<table class="form-table">';
    foreach ($meta_fields as $field) {
        // get value of this field if it exists for this post
        $meta = get_post_meta($post->ID, $field['id'], true);
        // begin a table row with
        echo '<tr>
				<th><label for="' . $field['id'] . '">' . $field['label'] . '</label></th>
				<td>';
        switch ($field['type']) {

            // text
            case 'text':
                echo '<input type="text" name="' . $field['id'] . '" id="' . $field['id'] . '" value="' . $meta . '" style="width:100%" />
                                                    <br /><span class="description">' . $field['desc'] . '</span>';
                break;

            // textarea
            case 'textarea':
                echo '<textarea style="width:100%" rows="2" id="' . $field['id'] . '" name="' . $field['id'] . '">' . $meta . '</textarea>
                                                    <br /><span class="description">' . $field['desc'] . '</span>';
                break;

            // checkbox
            case 'checkbox':
                echo '<input type="checkbox" name="' . $field['id'] . '" id="' . $field['id'] . '" ', $meta ? ' checked="checked"' : '', '/>
                                                    <label for="' . $field['id'] . '">' . $field['desc'] . '</label>';
                break;

            // select
            case 'select':
                echo '<select name="' . $field['id'] . '" id="' . $field['id'] . '">';
                foreach ($field['options'] as $option) {
                    echo '<option', $meta == $option['value'] ? ' selected="selected"' : '', ' value="' . $option['value'] . '">' . $option['label'] . '</option>';
                }
                echo '</select><br /><span class="description">' . $field['desc'] . '</span>';
                break;
        } //end switch
        echo '</td></tr>';
    } // end foreach
    echo '</table>'; // end table
}

// Save the Data
function onepix_save_custom_meta($post_id) {
    global $onepix_meta_fields;
    global $onepix_post_meta_fields;

    // verify nonce
    if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
        return $post_id;
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return $post_id;
    } elseif (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }

    //either post or page fields we'll be working with
    $fields;

    // Check permissions (pages or posts)
    if ('page' == $_POST['post_type']) {

        $fields = $onepix_meta_fields;
    } else if ('post' == $_POST['post_type']) {

        $fields = $onepix_post_meta_fields;
    }

    // loop through fields and save the data
    foreach ($fields as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    } // end foreach
}

add_action('save_post', 'onepix_save_custom_meta');
?>

I won’t explain how to add a meta box too much here. You can read up on? a good maintainable way to do it in this article: Reusable Custom Meta Boxes Part 1: Intro and Basic Fields. Basically the above code checks to see if it’s a page or a post we’re dealing with, then adds a meta box with appropriate field types based on the array of properties you feed it. It’s a little extra code than basic implementation, but it’s definitely worth it in the end since you’ll likely want to add more metabox fields in the future.

Once the meta box field is visible in your post edit area, you should be able to past embed code from YouTube or some other source into it and save it without any problems.

 

Modify the Featured Image In the Template File

Now that our embed code is safely stored within our post meta we need to be able to display it. Find the code that displays your featured images in your theme or plugin template files. they could be in a custom template file, your archives.php file, your post.php file depending on your situation. In any case you should likely have 2 areas to change: your post thumbnails featured image display, and your single post featured image display.

For the post thumbnail display you can look for something like this:

<?php the_post_thumbnail(); ?>

For the single post featured image, it may look something like this:

<?php echo the_post_thumbnail( 'single-post' ); ?>

Paste this in it’s place where appropriate:

<?php if (has_post_thumbnail()) { ?>

<!--    show the featured image-->
        <?php the_post_thumbnail(); ?>

<?php } else if (get_post_meta(get_the_ID(), 'onepix_video_embed', true)) { ?>

<!--    show the featured video-->
        <div class="videoWrapper">
            <?php echo get_post_meta(get_the_ID(), 'onepix_video_embed', true); ?>
        </div>

<?php } else { ?>

        <!--if no featured image or thumbnail, do something...-->

<?php } ?>

You’ll probably have to modify this to suit your theme, but you get the idea. Also notice the? “videoWrapper” div. We’ll talk about this in the next step. Our intention will be to show the video instead of the featured image if the embed code is present. We do this by echoing the posts video embed code meta that we just created and saved.? If all is well, you should now be able to see your video as a featured image in your blog post.

 

Making it Responsive

If you don’t need it to be responsive, you can stop right here, most however will be dealing with responsive themes and would like our videos to adapt accordingly. In order to do this, we’ll use some css tricks. There are many ways to do this, but by using css we can avoid too many JavaScript libraries in our theme or plugin.

Add this to your style.css file:

/*the featured video embed wrapper to make the iframe fluid*/
/*must have 16:9 ration or same proportions as 640*385 for this to work properly*/
.videoWrapper {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    padding-top: 25px;
    height: 0;
}

.videoWrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

This will automatically make your video responsive even though you set your iframe width and height in your embed code.
It’s kind of a cheat so take note that this is based on a 16:9 aspect ratio, meaning that your featured image has to have the same proportions of standard internet videos. For example, your responsive video will work as it should if it’s set to:? width=”640″ height=”385″ in the embed code, or anything with those same proportions.

 

 

 

Related Posts

Share This

Related Tags

no comments yet but open for them

Post a Reply

Your email address will not be published. Required fields are marked *