• Hi everybody!
    What this plugin does is find out a Youtube video embed in the body of the post, extract the video id and automatically create a custom field with the thumbnail address (ex. https://img.youtube.com/vi/AMXkiX9Hr_o/default.jpg).
    My problem is that in my video-blog I embed video by using a custom field (with key “embed”), and not adding it normally to the post.
    How can I use the function “preg_match” with the custom field “embed”?
    I hope to have been clear… sorry for my english and thanks for your help!

    <?php
    /*
    Plugin Name: YouTubeThumb2CustomField
    Plugin URI: https://herrpfleger.de/wp-plugin
    Description: Inserts URL to YouTube-thumbnail into Custom Field when you embed YouTube video into your post.
    Author: Herr Pfleger
    Version: 0.8
    Author URI: https://herrpfleger.de
    */

    add_action(‘save_post’,’find_ytid’, 10, 2);

    function find_ytid($postID, $post) {
    if($parent_id = wp_is_post_revision($postID))
    {
    $postID = $parent_id;
    }
    $content = $_POST[‘content’];
    if (preg_match(‘/http:\/\/www.youtube\.com\/v\/([a-zA-Z0-9\-\_]{11})/’, $content, $yturl) !=”) {
    $ytid = substr($yturl[0], 25, 31);
    $custom = ‘https://img.youtube.com/vi/&#8217;.$ytid.’/hqdefault.jpg’;
    update_custom_meta($postID, $custom ,’ytthumb_url’);
    }
    elseif (preg_match(‘/http(v|vh|vhd):\/\/([a-zA-Z0-9\-\_]+\.|)youtube\.com\/watch(\?v\=|\/v\/)([a-zA-Z0-9\-\_]{11})([^<\s]*)/’, $content, $yturl) !=”) {
    $custom = ‘https://img.youtube.com/vi/&#8217;.$yturl[4].’/hqdefault.jpg’;
    update_custom_meta($postID, $custom ,’ytthumb_url’);
    }
    }

    function update_custom_meta($postID, $newvalue, $field_name) {
    // To create new meta
    if(!get_post_meta($postID, $field_name)){
    add_post_meta($postID, $field_name, $newvalue);
    }else{
    // or to update existing meta
    update_post_meta($postID, $field_name, $newvalue);
    }
    }
    ?>

  • The topic ‘Preg_match from a custom field’ is closed to new replies.