Customize Embedded Tweets (or, How To Hide Photos in Embedded Tweets)

Here’s one way using the oembed_fetch_url filter to add the hide_media query parameter, that’s also mentioned in the Twitter doc page you linked to:

Set an oEmbed query parameter of hide_media=true or add a
data-cards="hidden" attribute to the resulting <blockquote> element to
prevent expanded content display.

Here’s an example:

/**
 * Hide media for all twitter oEmbeds, using the hide_media=1 query argument
 */
add_filter( 'oembed_fetch_url', function( $provider, $url, $args )
{
    // Target publish.twitter.com provider
    if( 'publish.twitter.com' === parse_url( $provider, PHP_URL_HOST ) )
        $provider = add_query_arg( 'hide_media', 1, $provider );

    return $provider;
}, 99, 3 );

Here’s how the Twitter provider url looks before:

https://publish.twitter.com/oembed?maxwidth=840&maxheight=1000&url=https%3A%2F%2Ftwitter.com%2FSamFlowers%2Fstatus%2F724417082247528448

and after:

https://publish.twitter.com/oembed?maxwidth=840&maxheight=1000&url=https%3A%2F%2Ftwitter.com%2FSamFlowers%2Fstatus%2F724417082247528448&hide_media=1

Then there’s the oembed_result to filter HTML returned by the provider. We could also use the embed_oembed_html filter to dynamically add the data-cards="hidden" attribute, even on a per post basis or check for our own custom query parameters. But I think the first method is more stable, since it’s harder to inject the attribute into a possibly dynamic HTML structure.


Leave a Comment