Allow iframes from specific sites?

With kses filtering, WordPress only allows a subset of html tags within a post or page, and one of the tags it strips out is the iframe tag (for many good reasons).

I'd like to allow editors to include iframes where the src is from one of our other subdomains, or from a specified whitelist of domains, but still strip out other unknown src's. It is straightforward to bypass kses to allow all iframe's, but is it possible to only allow certain domains?

Topic wp-kses iframe Wordpress

Category Web


I'd register an embed handler with wp_embed_register_handler. This gives you the added benefit of being able to just copy and paste the url into the editor as well as seeing a preview of the iframe.

add_action( 'init', 'se238330_register_embed_handler' );

function se238330_register_embed_handler() {
    wp_embed_register_handler( 
        'joetek',
        '#http://subdomain.yourdomain\.com/(.+)/?#i',
        'wp_embed_handler_joetek'
    );
}

function wp_embed_handler_embed_name( $matches, $attr, $url, $rawattr ) {
    $embed = sprintf(
        '<iframe class="joetek-website" src="http://subdomain.yourdomain.com/%1$s/" width="600" height="400" frameborder="0" scrolling="no"></iframe>',
        esc_attr( $matches[1] )
    );

    return apply_filters( 'embed_joetek', $embed, $matches, $attr, $url, $rawattr );
}

The code above assumes that joetek is the name of your embed :) You'd need to update the regex in the second parameter of wp_embed_register_handler as well as in the callback function to match the pages you want to be able to embed on your website.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.