How to detect YouTube iframe tag in a specific WordPress post

Detecting YouTube Iframes in WordPress Posts

This document outlines two primary methods for detecting YouTube iframe tags within the content of a specific WordPress post: one using PHP (server-side) and another using JavaScript (client-side).

Method 1: Using PHP (Server-Side)

This method is useful if you need to process the post content before it’s sent to the browser, for example, to modify it, count videos, or perform server-side logic.

Steps:

  1. Get the Post Content: You’ll need to fetch the content of the specific WordPress post.
  2. Use Regular Expressions: PHP’s preg_match_all function is ideal for finding all occurrences of a pattern within a string. We’ll construct a regular expression to match YouTube iframe URLs.

PHP Code Example:

<?php
/**
 * Function to detect YouTube iframes in a given post ID's content.
 *
 * @param int $post_id The ID of the WordPress post.
 * @return array An array of found YouTube iframe URLs, or an empty array if none are found.
 */
function detect_youtube_iframes_php($post_id) {
    // Get the post object
    $post = get_post($post_id);

    // Check if the post exists and has content
    if (!$post || empty($post->post_content)) {
        return [];
    }

    $post_content = $post->post_content;

    // Regular expression to find YouTube iframe src attributes.
    // It looks for iframes with src containing "youtube.com/embed/" or "youtube-nocookie.com/embed/".
    // It captures the entire URL within the src attribute.
    $pattern = '/<iframe[^>]+src=["\'](https?:\/\/(?:www\.)?(?:youtube\.com|youtube-nocookie\.com)\/embed\/[^"\'\s]+)["\'][^>]*><\/iframe>/i';

    $matches = [];
    // Perform the regex match to find all occurrences
    preg_match_all($pattern, $post_content, $matches);

    // $matches[1] will contain the captured URLs from the src attribute
    if (!empty($matches[1])) {
        return $matches[1];
    }

    return [];
}

// --- Example Usage ---

// Replace with the actual ID of the WordPress post you want to check
$target_post_id = 123; // Example post ID

$youtube_urls = detect_youtube_iframes_php($target_post_id);

if (!empty($youtube_urls)) {
    echo "<h2>Found YouTube Videos in Post ID: {$target_post_id}</h2>";
    echo "<ul>";
    foreach ($youtube_urls as $url) {
        echo "<li>" . esc_html($url) . "</li>";
    }
    echo "</ul>";
} else {
    echo "<p>No YouTube iframes found in Post ID: {$target_post_id}.</p>";
}

?>

Explanation of the PHP Regular Expression:

  • /<iframe[^>]+src=["\'](...)["\'][^>]*><\/iframe>/i
    • <iframe: Matches the literal opening <iframe> tag.
    • [^>]+: Matches one or more characters that are not >. This accounts for other attributes like width, height, frameborder, etc.
    • src=["\']: Matches the src= attribute followed by either a double or single quote.
    • (https?:\/\/(?:www\.)?(?:youtube\.com|youtube-nocookie\.com)\/embed\/[^"\'\s]+): This is the capturing group that gets the actual URL.
      • https?:\/\/: Matches http:// or https://.
      • (?:www\.)?: Optionally matches www.. (?:...) is a non-capturing group.
      • (?:youtube\.com|youtube-nocookie\.com): Matches either youtube.com or youtube-nocookie.com.
      • \/embed\/: Matches the /embed/ path, which is common for YouTube iframes.
      • [^"\'\s]+: Matches one or more characters that are not a double quote, single quote, or whitespace. This captures the rest of the URL until the closing quote.
    • ["\']: Matches the closing quote for the src attribute.
    • [^>]*: Matches any characters until the closing > of the iframe tag.
    • <\/iframe>: Matches the literal closing </iframe> tag.
    • /i: The i flag makes the regex case-insensitive.

Method 2: Using JavaScript (Client-Side)

This method is executed in the user’s browser after the page has loaded. It’s useful for dynamic interactions or if you need to perform actions based on the iframes present on the page without server-side processing.

Steps:

  1. Wait for DOM Load: Ensure the HTML document is fully loaded before trying to access elements.
  2. Select All Iframes: Use document.querySelectorAll('iframe') to get all iframe elements on the page.
  3. Filter for YouTube Iframes: Iterate through the found iframes and check their src attribute to see if it belongs to YouTube.

JavaScript Code Example:

<script>
document.addEventListener('DOMContentLoaded', function() {
    /**
     * Function to detect YouTube iframes on the current page.
     *
     * @returns {Array<string>} An array of found YouTube iframe URLs, or an empty array if none are found.
     */
    function detectYoutubeIframesJS() {
        const iframes = document.querySelectorAll('iframe');
        const youtubeUrls = [];

        iframes.forEach(iframe => {
            const src = iframe.getAttribute('src');
            // Check if the src attribute exists and contains a YouTube embed URL pattern
            if (src && (src.includes('youtube.com/embed/') || src.includes('youtube-nocookie.com/embed/'))) {
                youtubeUrls.push(src);
            }
        });

        return youtubeUrls;
    }

    // --- Example Usage ---
    const foundYoutubeUrls = detectYoutubeIframesJS();

    const resultDiv = document.createElement('div');
    resultDiv.style.marginTop = '20px';
    resultDiv.style.padding = '15px';
    resultDiv.style.backgroundColor = '#f0f9ff';
    resultDiv.style.border = '1px solid #cceeff';
    resultDiv.style.borderRadius = '8px';
    resultDiv.style.fontFamily = 'Inter, sans-serif';

    if (foundYoutubeUrls.length > 0) {
        let htmlContent = '<h2>Found YouTube Videos on this Page:</h2><ul>';
        foundYoutubeUrls.forEach(url => {
            htmlContent += `<li><a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a></li>`;
        });
        htmlContent += '</ul>';
        resultDiv.innerHTML = htmlContent;
    } else {
        resultDiv.innerHTML = '<p>No YouTube iframes found on this page.</p>';
    }

    // Append the result to the body or a specific element
    document.body.appendChild(resultDiv);
});
</script>

Explanation of the JavaScript Code:

  • document.addEventListener('DOMContentLoaded', function() { ... });: This ensures the script runs only after the entire HTML document has been loaded and parsed, preventing errors if iframes haven’t been rendered yet.
  • document.querySelectorAll('iframe'): This selects all <iframe> elements present in the current document.
  • iframe.getAttribute('src'): Retrieves the value of the src attribute for each iframe.
  • src.includes('youtube.com/embed/') || src.includes('youtube-nocookie.com/embed/'): This is a simple and effective way to check if the src URL contains the characteristic YouTube embed path.

Considerations:

  • WordPress Embeds: WordPress often converts plain YouTube links into iframes automatically using oEmbed. Both methods above will correctly detect these generated iframes.
  • Security: When dealing with user-generated content, always be mindful of sanitization. The methods above are for detection, not for sanitizing input.
  • Performance: For very large posts or many posts, server-side regex can be resource-intensive. Client-side detection happens in the user’s browser and doesn’t impact server load as much.
  • Variations: While the provided regex and JavaScript checks cover standard YouTube embeds, very unusual or custom embed codes might require adjustments to the detection logic.

Choose the method that best fits where and when you need to perform the detection. PHP is for server-side processing before the page is rendered, while JavaScript is for client-side interaction after the page is visible.

Related Posts


Why Apple Pay Isn’t Showing on WooCommerce Authorize.Net Checkout (SkyVerge)

It’s understandable to be frustrated when you’ve meticulously followed all the steps for...

How to Change the Active Link Color in Navigation Menu Using CSS: The Ultimate Guide

Having proper visual feedback in your website’s navigation is crucial for both user experience...

Limit total quantity globally for specific product category in WooCommerce

To limit the total quantity globally for a specific product category in WooCommerce, you can use a c...

Can You Customize Template Parts Per Page Template in WordPress? Yes—Here’s How

Yes, you can absolutely customize template parts per page template in WordPress! This is a common an...

Recent Posts