Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coppa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Come impostare la larghezza massima di oEmbed in WordPress (4 metodi semplici)

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

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.

Setting oEmbed maximum width in WordPress

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.

A WordPress embed overflowing the content width

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:

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.

Embed shortcode width

Quando si è soddisfatti della pagina, basta cliccare su “Aggiorna” o “Pubblica”.

Il contenuto incorporato dovrebbe ora adattarsi perfettamente allo spazio disponibile.

oEmbed width adjusted

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.

Embed blocks in WordPress

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”.

Adding aligning to an embed block in WordPress

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.

Adding a code snippet to WordPress

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”.

Adding a PHP code snippet to WordPress

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.

Activating a custom PHP snippet

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”.

Chrome's inspect tool

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.

Finding CSS classes for embed blocks

È 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”.

Adding a CSS snippet to WordPress

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.

An example of an embedded social media post, created using Smash Balloon

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.

An example of an embedded Facebook timeline, created using Smash Balloon

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.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

44 commentiLascia una risposta

  1. 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!

  2. 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

  3. 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!

  4. 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!

  5. 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.

  6. 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,

    • 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…

      add_filter('embed_defaults','yourthemename_embed_defaults');
  7. 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?

  8. 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….

  9. 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

  10. 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…

  11. 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!

  12. 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?

  13. 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

  14. 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!

    • 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.

        • 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.

  15. 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

      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

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.