Volete limitare la larghezza degli oEmbed in WordPress?
WordPress incorpora automaticamente contenuti di terze parti, come video di YouTube e tweet. Tuttavia, a volte gli incorporamenti possono diventare troppo ampi e rovinare il design del sito web.
In questo articolo vi mostreremo come impostare la larghezza massima di oEmbed in WordPress in modo da avere un maggiore controllo sul layout del sito.
Perché correggere la larghezza massima di OEmbed in WordPress?
WordPress supporta oEmbed, che consente di incorporare automaticamente contenuti da siti web di terzi. Ad esempio, è possibile incorporare facilmente video di YouTube, presentazioni di SlideShare, tweet e molti altri tipi di contenuti.
Questo contenuto non è ospitato sul vostro server, quindi non rallenterà il vostro sito web. In particolare, dovreste sempre utilizzare tecnologie come oEmbed e non caricare mai un video su WordPress.
Nota: sebbene Facebook e Instagram abbiano supportato entrambi l’oEmbed in passato, Meta ha abbandonato il supporto per l’oEmbed. Per istruzioni passo passo su come riparare questa funzione, consultate la nostra guida su come risolvere il problema di Facebook e Instagram oEmbed in WordPress.
WordPress cercherà sempre di regolare la larghezza del contenuto incorporato in modo che si adatti perfettamente allo spazio disponibile. Tuttavia, a volte il contenuto incorporato può essere troppo largo e sovrapporsi alle altre aree di contenuto del sito web.
Purtroppo, non è possibile impostare una larghezza massima per gli embed di terze parti utilizzando gli strumenti integrati di WordPress.
Detto questo, vediamo come aggiungere questa funzione mancante e impostare una larghezza massima di oEmbed in WordPress. Utilizzate semplicemente i collegamenti rapidi qui sotto per passare direttamente al metodo che desiderate utilizzare:
- Method 1: Using the Embed Shortcode (Best for YouTube Videos)
- Method 2: Using the Built-in WordPress Embed Blocks (Easy)
- Method 3: Using Custom PHP (Set a Max Width for All Embeds)
- Method 4: Using CSS (Set Max Width for Specific Embed Types)
- Bonus Tip: How to Easily Add Your Social Media Feeds to WordPress
Metodo 1: Utilizzo dello shortcode di incorporamento (migliore per i video di YouTube)
È possibile impostare una larghezza massima utilizzando uno shortcode. Questo metodo è semplice, soprattutto se si desidera impostare la larghezza massima solo per un numero ridotto di post. Abbiamo riscontrato che questo metodo funziona bene anche per incorporare i video nei post del blog WordPress.
Tuttavia, lo shortcode embed e i suoi parametri di larghezza e altezza non funzionano per tutti i fornitori di oEmbed. Ad esempio, non è possibile utilizzarlo per impostare l’altezza e la larghezza di un embed di Giphy in WordPress. In questo caso, potete provare uno degli altri metodi indicati di seguito.
Invece di incollare l’URL nell’editor del post, è necessario creare un blocco shortcode. È quindi possibile aggiungere i parametri di larghezza e altezza al codice embed.
Ad esempio, è sufficiente avvolgere quanto segue nei tag embed
:
width="900" height="600"]https://www.youtube.com/watch?v=6LwWumPeues
È sufficiente modificare i valori di larghezza e altezza in base alle proprie esigenze e sostituire l’URL con il contenuto che si desidera incorporare.
Quando si è soddisfatti della pagina, basta cliccare su “Aggiorna” o “Pubblica”.
Il contenuto incorporato dovrebbe ora adattarsi perfettamente allo spazio disponibile.
Metodo 2: Utilizzare i blocchi incorporati di WordPress (facile)
L’editor di blocchi di WordPress è dotato di diversi blocchi di incorporamento per diversi servizi oEmbed.
Alcuni di questi blocchi consentono di modificare l’allineamento dell’embed e di impostare il contenuto su “larghezza ampia” o “larghezza piena”.
Se si sceglie la larghezza massima, il blocco incorporato e il contenuto incorporato occuperanno l’intera larghezza dello schermo. Se si sceglie la larghezza ampia, il blocco incorporato occuperà l’intera larghezza, ma il contenuto rimarrà della stessa dimensione.
Il risultato finale può variare a seconda del vostro tema WordPress. Tuttavia, si tratta di un metodo semplice e veloce, quindi vale la pena di verificare se funziona per il vostro sito WordPress.
È sufficiente fare clic sul pulsante “Allinea” nella piccola barra degli strumenti sopra il blocco. Quindi, selezionare “Larghezza ampia” o “Larghezza intera”.
Se questo risolve il problema della larghezza massima dell’embed, si può procedere alla pubblicazione della pagina. Se non si è soddisfatti dell’aspetto, è necessario provare un altro metodo.
Metodo 3: Usare PHP personalizzato (impostare una larghezza massima per tutti gli incorporamenti)
A volte si può desiderare di impostare una larghezza massima per tutti i contenuti incorporati. Il modo più semplice per farlo è aggiungere un codice personalizzato al vostro sito WordPress.
Il problema di questo metodo è che l’attributo di larghezza massima funziona solo se il contenuto incorporato non ha già una “larghezza” definita. Se il codice incorporato include già il proprio attributo ‘width’, questo metodo potrebbe non funzionare.
Se non avete mai modificato il codice del vostro sito, date un’occhiata alla nostra guida su come aggiungere facilmente snippet di codice personalizzati in WordPress.
Alcune guide chiedono di modificare manualmente i file del tema, ma questo può causare errori comuni di WordPress e può persino distruggere completamente il vostro sito web.
Per questo motivo, consigliamo di utilizzare WPCode. Consente di aggiungere facilmente snippet di codice in WordPress senza dover modificare i file del tema. In questo modo, è possibile aggiornare o modificare il tema senza perdere tutte le funzioni del codice personalizzato.
Per prima cosa, è necessario installare e attivare il plugin gratuito WPCode. Per ulteriori informazioni, consultate la nostra guida passo-passo su come installare un plugin di WordPress.
Dopo l’attivazione, andare su Code Snippets ” Add Snippet.
Nella schermata successiva, passare il mouse sull’opzione “Aggiungi codice personalizzato (nuovo snippet)” e fare clic sul pulsante “Usa snippet” quando appare.
Nella schermata successiva, digitate un titolo per lo snippet di codice. Questo è solo un riferimento, quindi potete usare qualsiasi cosa vogliate.
Quindi, aprire il menu a tendina “Tipo di codice” e scegliere “Snippet PHP”.
A questo punto, è sufficiente incollare quanto segue nell’editor di codice:
add_filter( 'embed_defaults', 'wpbeginner_embed_defaults' );
function wpbeginner_embed_defaults() {
return array(
'width' => 400,
'height' => 280
);
}
Non dimenticate di regolare gli attributi di altezza e larghezza in base alle vostre esigenze.
Infine, fare clic sul cursore “Inattivo”, in modo da visualizzare “Attivo”. Quindi basta fare clic sul pulsante “Salva snippet” o “Aggiorna” per rendere attivo lo snippet di codice.
Metodo 4: Utilizzo dei CSS (Impostazione della larghezza massima per tipi specifici di incorporazioni)
Per impostazione predefinita, WordPress aggiunge automaticamente le classi CSS alle diverse aree del sito.
Aggiunge anche diverse classi CSS ai blocchi di incorporamento. È possibile utilizzare queste classi CSS per impostare una larghezza massima per gli embed sul proprio blog WordPress.
È una buona scelta se si desidera impostare una dimensione massima per un tipo specifico di incorporamento, come i Tweet incorporati. Consente anche di creare una dimensione massima per tutti i contenuti incorporati, indipendentemente dal tipo.
Per sapere quali sono le classi CSS da selezionare, è sufficiente incorporare il contenuto in un post o in una pagina e visualizzarlo in anteprima nel browser.
Quindi, passare il mouse sul contenuto incorporato e fare clic con il tasto destro del mouse. Nel menu che appare, selezionare lo strumento “Ispezione”.
Si apre un nuovo pannello che mostra tutte le classi CSS che WordPress ha aggiunto al contenuto incorporato. È possibile utilizzare queste classi per impostare una larghezza massima per questo tipo di incorporamento.
Per puntare a uno specifico fornitore di oEmbed, di solito si usa .wp-block-embed-providername
, quindi cercate questa classe nel pannello.
Ad esempio, nell’immagine seguente, abbiamo sottolineato la classe .wp-block-embed-providername
. Su questa riga, possiamo vedere anche una classe .wp-block-embed-pinterest
.
È possibile impostare una larghezza massima solo per gli embed di Pinterest utilizzando la classe .wp-block-embed-pinterest
.
Ad esempio:
.wp-block-embed-pinterest {
max-width: 900px!important;
}
Si tenga presente che potrebbe essere necessario sostituire .wp-block-embed-pinterest
con una classe CSS diversa, a seconda del contenuto che si desidera indirizzare.
Se si vuole impostare una larghezza massima per tutti gli incorporamenti, si può usare il seguente snippet:
.wp-block-embed {
max-width: 900px!important;
}
Il modo più semplice per aggiungere CSS personalizzati al proprio sito web è utilizzare WPCode. È sufficiente creare un nuovo snippet personalizzato seguendo la stessa procedura descritta sopra.
Tuttavia, questa volta aprite il menu a tendina “Tipo di codice” e selezionate “Snippet CSS”.
Ora è possibile salvare e pubblicare questo snippet esattamente nello stesso modo in cui si rende vivo qualsiasi snippet di WPCode.
Fatto ciò, WordPress utilizzerà questo valore come dimensione massima per i vostri embed.
Suggerimento bonus: come aggiungere facilmente i feed dei social media a WordPress
Se incorporerete regolarmente contenuti dalle piattaforme dei social media, potrete risparmiare molto tempo e fatica utilizzando Smash Balloon.
Smash Balloon è il miglior plugin di social media per WordPress e consente di aggiungere facilmente i feed dei social media a un sito web WordPress.
Supporta tutti i social media più diffusi, tra cui YouTube, Twitter e Instagram.
Inoltre, Smash Balloon risponde alle esigenze dei dispositivi mobili e funziona con qualsiasi tema di WordPress, per cui i contenuti incorporati avranno sempre un aspetto eccellente.
Speriamo che questo articolo vi abbia aiutato a capire come impostare la larghezza massima di un oEmbed in WordPress. Potreste anche voler consultare la nostra scheda completa sui social media o il nostro confronto di esperti tra i migliori software di live chat per le piccole imprese.
Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.
Syed Balkhi says
Hey WPBeginner readers,
Did you know you can win exciting prizes by commenting on WPBeginner?
Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
You can get more details about the contest from here.
Start sharing your thoughts below to stand a chance to win!
Andreu says
The problem of this is that it makes the max width of the images also to the size defined. What can I do if I want to limit the embed width in the editor but not the image one? Thanks
Joe Daniel says
Thank you. I’ve been struggling with this for weeks… works for WP 4.0 with Genesis theme
digg says
Hi, it works perfectly for me.
But this affects to the overall site, which have different widths since there are full-width pages, with sidebars, or forums, etc.
Is it possible to discriminate this to affect only bbpress forum’s pages?
It will be very useful, thanks!
Ajit Kumar says
For anybody who can’t get this working or if Youtube videos and other iframe content are not getting resized, you will need to add the following code to your style.css
/* Make sure embeds and iframes fit their containers */
embed,
iframe,
object {
max-width: 100%;
}
Hope this helps. And Syed, thanks for the great post!
Waymond says
Thanks for posting the solution!
Abhishek Sachan says
not working
Dj says
THANKS! This was driving me crazy.
Anto (@imanto) says
You can’t use iframe, object, embed { max-width: 100%; height:auto;} yes it gets the width correct and makes the video responsive, but it doesnt fix the height when viewing in the browser.
Is there actually a way to do this? Ive tried pretty much everything, even fitvids dont work because you are setting a px base width in the functions, but it shows that width on mobile, then when you try to correct that with max-width, the height messes up even in the browser….
im thinking media queries or something? ugh im beat.
Amir says
Works perfect, thanks a lot!
Pierre Dickinson says
Hi, thanks for the tip, but it doesn’t work, here’s what you need in your function.php file :
add_filter(‘embed_defaults’,’yourthemename_embed_defaults’);
function yourthemename_embed_defaults($defaults) {
$defaults[‘width’]=600; // or whatever you want
$defaults[‘height’]=360; // or whatever you want
return $defaults;
}
it works great!
Regards,
Filip Kojic says
This code doesnt work well. I put my theme name and theme just blocks.
Valerie says
Not sure if the other commenter realized it, but the code has curly quotes and would break a site. Gonna test here to see if shortcode wrappers will prevent the change that broke the code…
John Cronin says
I am attempting to post a high-end animation film from YouTube to my WordPress blog. The bottom of the frame is cut off in the preview. Once the play arrow is clicked, this problem goes away. But the filmmaker is rightfully unhappy that the preview in the post will give the appearance of an error. Adjusting height and width in the post code works, but does not solve the problem. Ideas?
Colin says
Worked like a charm – thanks!
Ryan Silver says
Hi there,
I used your solution for width and it worked great. But how do I set the height now? Is it just the same if ( ! isset( $content_width ) ) $content_width = 560; but with the word ‘width’ is replaced with the word ‘height’ ? I tried that and it did not work….
Editorial Staff says
The height is auto-determined to match the 16:9 ratio.
Admin
FIlip Kojic says
It looks like it is 16:10. Here is example:
How can I change height. Please someone answer.
Jasmine Ham says
greats, it’s working! but what if i need it to be responsive?
any idea to doing that?
josef says
hi,
is there a way to force all ifreams in the site to be 100% widht. not omly youtube
i have about 300 ifreams and all fixed size so… thanks in advance
Josef
josef says
hi,
is there a way to force all ifreams in the site to be 100% widht. not omly youtube
i have about 300 ifreams and all fixed size so…
Ryan says
I added this code to my functions.php but it made no difference, and I assume that’s because my theme doesn’t define $content_width.
I see the link to the codex about defining it, but I’m not a developer and don’t have one on call; how does one add a $content_width definition to a theme? Where does it go? Thanks!
Justin Germino says
This worked perfectly, is there anyway to force and default the video to HD quality instead of SD quality which seems to be the default even though in my YouTube settings I have it set to default to HD?
Editorial Staff says
What is your max width? I have read in the past that Youtube adjusts quality based on the width of the iframe.
Admin
Grant Norwood says
Please note that the $content_width variable must be declared as global before this fix will work.
Nigel Parry says
WP seems to be updated by people who are unclear about the centrality of multimedia on the Internet. Why this basic preference would have to require code intervention I don’t know. WP clearly could not tell how wide my columns were. Anyway, all fixed now. You folks rock.
Editorial Staff says
Well Nigel, there is more to it. They are trying to make WordPress easier to use for “users”. Overtime, WordPress has added one option after another. This gets really terrifying for new users. This is why they are going with decisions over options route. The hope with this oEmbed max width is that each theme designer should/will define it in their themes, so the end-user doesn’t have to worry about it.
Admin
Alex Leonard says
Thanks! I was a little baffled as to where the media embed setting had gone to!
Azad says
Hello
Thanks for your post.
But I can’t get this right, I wrote the other post you mentioned in the comments. But I still can’t get it working, I put this:
At the begginin of my functions.php, but then my whole site stoped working. everything turned white, I had to edit the file through ftp to get it working again.
What am I doing wrong?
Thanks!
Azad says
Hey
I got it working, thanks!
Monica says
Hi, where in the functions.php file should this code be placed?
Editorial Staff says
You can paste it in the beginning or at the end as long as it is independent of other functions. Here is an article on that:
https://www.wpbeginner.com/beginners-guide/beginners-guide-to-pasting-snippets-from-the-web-into-wordpress/
Admin
Jesse Garnier says
What value would be appropriate for $content_width for a variable-width or responsive design?
Editorial Staff says
For responsive design, you probably want to use fitvid.js or something similar to resize your videos.
Admin
Paul Lumsdaine says
I was able to kind of get the responsiveness to work with setting a max-width: 100% on my iframes in CSS. Of course the height is set automatically depending on your content width but this should at least get it working correctly without using any extra js. Fitvid is the way to go, but this worked for me.
Jeremy Myers says
Paul,
Can you include the css you used to set your iframe width to 100%?
Roman says
I use this CSS code for responsive design:
iframe, object, embed { max-width: 100%; } ( if you want you can add -> height: auto )
Tevya says
Unfortunately Roman’s CSS either doesn’t work on some themes or doesn’t work with the new WP 3.6 media player that’s built-in to core. I just tried it and nothing. I’m trying to get a theme that’s responsive to keep the new WP 3.6 player responsive as well, but no luck so far. The 2012 theme seems to handle it very nicely, but I can’t figure out what they’re doing different than this theme I’m working with.
Melanie says
I am a novice to WP & coding, with that said not sure where to put the code “if ( ! isset( $content_width ) ) $content_width = 600;” I went to the function.php file in my Suffusion theme and not sure where exactly to insert this code. I tried a number of places where it mentioned video attachment and it is not working. In my case, the embedded videos are now too big for my theme since upgrading to WP 3.5.
Editorial Staff says
Change the number 600 to match your theme size. If it is too big for your theme, then make it smaller.
Admin
Jessi Linh says
It’s been released at right time!!! The name “Elvin” is so special,too.
Thanks for your post.
Edward Caissie says
This is part of the reason setting an appropriate $content_width value is a requirement under the WordPress Theme Review guidelines (http://codex.wordpress.org/Theme_Review#Required_Hooks_and_Navigation)
Editorial Staff says
Yup, totally agreed with you there. Only poorly coded themes will not have that. But there are a lot of those out there. A theme that one of our clients was using had that piece missing. Overall, its a good theme.
Admin
Devin says
Perfect timing. Thank you!