Halloween Sale 15% off Ends in See the plans
PHP

Sandbox Iframes From Untrusted Sites in Your Content

Adds a restrictive sandbox to iframes in posts that come from sites not on your trusted list, so an embedded page cannot redirect your visitors, open pop-ups or run scripts against your site.

Don’t have WPIDE yet? Install it on your site

Code

// Hosts whose iframes are left alone (subdomains included).
$wpide_trusted_frames = array( 'youtube.com', 'youtube-nocookie.com', 'vimeo.com', 'google.com', 'spotify.com', 'soundcloud.com' );

add_filter( 'the_content', function ( $content ) use ( $wpide_trusted_frames ) {
    if ( false === stripos( $content, '<iframe' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
        return $content;
    }

    $own  = wp_parse_url( home_url(), PHP_URL_HOST );
    $tags = new WP_HTML_Tag_Processor( $content );

    while ( $tags->next_tag( 'iframe' ) ) {
        $host = strtolower( (string) wp_parse_url( (string) $tags->get_attribute( 'src' ), PHP_URL_HOST ) );

        if ( ! $host || $host === $own || null !== $tags->get_attribute( 'sandbox' ) ) {
            continue;
        }

        foreach ( $wpide_trusted_frames as $trusted ) {
            if ( $host === $trusted || substr( $host, -strlen( '.' . $trusted ) ) === '.' . $trusted ) {
                continue 2;
            }
        }

        $tags->set_attribute( 'sandbox', 'allow-scripts allow-same-origin allow-forms' );
        $tags->set_attribute( 'referrerpolicy', 'no-referrer' );
    }

    return $tags->get_updated_html();
}, 20 );

Notes

Add every service you embed on purpose to $wpide_trusted_frames; sandboxed embeds from other sites may lose some features.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.