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

I’m relying on the WP functionality to embed a tweet. When I add a tweet URL, like so:

https://twitter.com/SamFlowers/status/724417082247528448

to the editor, it expands and shows the following:

Embedded tweet displayed in WordPress

I never have to directly touch the embed code from Twitter. However, I’d like to customize the tweet so that it doesn’t display the image. According to the Twitter docs, in order to hide photos, I need to add:

 data-cards="hidden"

to the blockquote generated by WordPress.

My question…

Since WordPress never directly shows me the embed code (not viable in the Visual or the Text tab of the editor), is there a way to automatically insert the ‘data-cards=”hidden”‘ code into the blockquote code for all tweets shown in the content areas on the website?

Thanks!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x