Fetch First Video Tag

User
we have a video tag under wordpress post content . now want to fetch first video from post content progrmamartically
Assistant
You can fetch the first “ tag from a WordPress post's content programmatically using PHP. Here's how you can do it:

### Method 1: Using `get_the_content()` and `DOMDocument`

function get_first_video_from_post($post_id) {
    $post = get_post($post_id);
    if (!$post) {
        return '';
    }

    $content = $post->post_content;

    // Load content into DOMDocument
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);
    libxml_clear_errors();

    $videos = $dom->getElementsByTagName('video');

    // Return first video tag if found
    if ($videos->length > 0) {
        return $dom->saveHTML($videos->item(0));
    }

    return '';
}

// Usage
$post_id = get_the_ID(); // Get current post ID
echo get_first_video_from_post($post_id);

### Method 2: Using `preg_match`
If you prefer regex, you can extract the first “ tag using `preg_match`:

function get_first_video_from_content($post_id) {
    $post = get_post($post_id);
    if (!$post) {
        return '';
    }

    $content = $post->post_content;

    // Match the first <video> tag
    preg_match('/<video.*?>.*?</video>/is', $content, $matches);

    return !empty($matches) ? $matches[0] : '';
}

// Usage
$post_id = get_the_ID(); // Get current post ID
echo get_first_video_from_content($post_id);

### Explanation:
– **Method 1**: Uses `DOMDocument` to parse the content and extract the first “ tag.
– **Method 2**: Uses `preg_match` to find the first “ tag.

Let me know if you need modifications! ๐Ÿš€

Leave a Comment

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