11
Php

Show Video In Excerpt

A few days ago I’ve developed a WordPress site and used Viper’s Video Quicktags plugin. The plugin works fine and it’s really awesome but on my site I wanted to use WordPress’ the_excerpt function instead of the_content and also I was trying to show video clips on my index page and that was a problem, not with the plugin but the_excerpt function strips out all HTML tags and doesn’t show video clips and basically it was built to show only the first 55 characters by default. So I’ve searched the Google and didn’t find any easy solution then I’ve tried to do something by myself and finally I’ve solved it using WordPress’s hook on the_excerpt. I’ve used the ‘the_excerpt’ filter and now it’s working fine. Here is the example I’m using in my functions.php file to filter ‘the_excerpt’ function.


function new_excerpt($text)
{
    global $post;
    $pattern = get_shortcode_regex();
    preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches );

    if(is_array( $matches ) && array_key_exists(2, $matches )) {
        //I'm currently using only youtube and flv videos. If you use
        //other videos then add those shortcodes in the following array
        $arr=array('youtube','flv');
        foreach($matches[2] as $v) {
            if(in_array($v, $matches[2])) {
                $vdo = apply_filters('the_content', $matches[0][0]);
                $text = get_the_excerpt();
                $text.= "
".$vdo."
"; } } } return $text; } add_filter('the_excerpt', 'new_excerpt');

Here is the live example.

Above code snippet solved my problem and videos are visible within the_excerpt function. Hope this one will help someone and if there is anything else better than this please let me know. Thanks!

Latest Blog

0
Php

PHP – 8.0 Match Expression

In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]

0
Php

New Union Type in PHP – 8

A new RFC has been finished voting and accepted for PHP – 8. That is “Union Types”, which is an extension of PHP’s type system. […]