Clifton's Exclusive VIP Blogging Strategies
Your name and email address will never be sold.

Resize Video Function ‘on the fly’ with PHP

I just wrote this function to resize video elements for my WordPress Lightbox Plugin. This specific script is designed to be used with an ajax call. Like this:

Let me know if you have any problems. I just rewrote most of this on the fly, so there may be errors. …but hopefully not. :)

jQuery / Javascript

Add this to your plugin’s javascript file between the

jQuery(function($){
    $('#video-code').bind('paste', function(){
        var field = $(this);
        setInterval(function(){
            var vall = $(field).val();
            var html = encodeURIComponent(val);
            $.post(ajaxurl, 'action=clp_resize_video&html='+html, function(response){
               $(field).val(response);
            });
        }, 150);
    });
});

PHP WordPress Function

This can be added to your plugin’s functions file.

add_action('wp_ajax_clp_size_video', 'clp_size_video');
function clp_size_video(){
    $new_width = 320;
    $video = stripslashes($_POST['html']);
    preg_match("/width="([^"]*)"/i",$video,$w);
    $w = (integer)$w[1];
    preg_match("/height="([^"]*)"/i",$video,$h);
    $h = (integer)$h[1];
    if(!$new_width)
        $new_width = $w;
    $w2 = $new_width;
    $ratio = (float)($w2/$w);
    $h2 = (integer)($h * $ratio);
    $video = str_replace("width="$w"","width="$w2"",$video);
    $video = str_replace("height="$h"","height="$h2"",$video);
    echo $video;
    die();
}

About Clifton Hatfield

He fell in love with the WordPress Publishing Platform and has been creating themes and plugins for it ever since. He is the kind of guy that can read code better than he can read a book. Often, you can find him hunched over a keyboard delivering his magic. He likes cold pizza, walking on moving sidewalks, and Indiana Jones.

0 comments