WordPress – filter video embed code

In WordPress, how do you filter a textarea that saves a vimeo embed code in theme admin? Using sanitize_text_field will make the code unusable when saving into db via update_post_meta.

    $postmeta = sanitize_text_field( $_POST['embed_video']);
    update_post_meta($post_id, 'embed_video',$postmeta );

Related posts

Leave a Reply

2 comments

  1. I often approach wordpress video embeds from the other angle, creating the embed code in the template, for example rather than have someone embed a video like this:

    <iframe src="http://player.vimeo.com/video/69277800?title=0&amp;byline=0&amp;portrait=0&amp;badge=0" width="577" height="325" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
    

    I’d have them just insert the id, in this case 69277800. Then I’d put in my template

    <?php if(!empty($video_id)):?>
    <iframe src="http://player.vimeo.com/video/<?php echo $video_id;?>?title=0&amp;byline=0&amp;portrait=0&amp;badge=0" width="577" height="325" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
    <?php endif;?>
    
  2. I would suggest that you save the video’s URL in a text input (continue using sanitize_text_field()) and then output the embed code using WordPress’s wp_get_oembed() function. This will work on a variety of allowed providers, such as Youtube and Vimeo. This method is safer as long as you are using allowed providers and I believe it is possible to add providers to the whitelist in the off-chance you are using someone pretty obscure.

    $input = get_post_meta( $post->ID, '_my_meta_input', true );
    echo wp_oembed_get( $input );
    

    Additionally, you can whitelist the iframe and sanitize the textarea using wp_kses() as shown in my answer here.