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

Cómo establecer el ancho máximo de oEmbed en WordPress (4 métodos fáciles)

Nota editorial: Ganamos una comisión de los enlaces de socios en WPBeginner. Las comisiones no afectan a las opiniones o evaluaciones de nuestros editores. Más información sobre Proceso editorial.

¿Quieres limitar el ancho de los oEmbeds en WordPress?

WordPress incrusta automáticamente contenidos de terceros, como vídeos de YouTube y Tweets. Sin embargo, a veces los contenidos incrustados pueden ser demasiado amplios y arruinar el diseño de su sitio web.

En este artículo, le mostraremos cómo establecer el ancho máximo de oEmbed en WordPress para que tenga más control sobre la disposición / disposición / diseño / plantilla de su sitio.

Setting oEmbed maximum width in WordPress

¿Por qué corregir la anchura máxima de OEmbed en WordPress?

WordPress es compatible con oEmbed, que permite incrustar automáticamente contenidos de sitios web de terceros. Por ejemplo, puedes incrustar fácilmente vídeos de YouTube, presentaciones de SlideShare, tweets y muchos otros tipos de contenido.

Este contenido no está alojado en tu servidor, por lo que no ralentizará tu sitio web. En particular, deberías utilizar siempre tecnologías como oEmbed, y nunca subir un vídeo a WordPress.

Nota: Aunque Facebook e Instagram eran compatibles con oEmbed en el pasado, Meta ha dejado de dar soporte a oEmbed. Para obtener instrucciones paso a paso sobre cómo reparar esta característica, consulta nuestra guía práctica sobre cómo corregir el problema de oEmbed de Facebook e Instagram en WordPress.

WordPress siempre intentará ajustar el ancho del contenido incrustado para que se ajuste perfectamente al espacio disponible. Sin embargo, a veces el contenido incrustado puede ser demasiado ancho y superponerse a otras áreas de contenido de tu sitio web.

A WordPress embed overflowing the content width

Lamentablemente, no es posible establecer una anchura máxima para incrustaciones de terceros mediante las herramientas integradas de WordPress.

Dicho esto, veamos cómo puedes añadir esta característica que falta y establecer un ancho máximo de oEmbed en WordPress. Simplemente utilice los enlaces rápidos a continuación para saltar directamente al método que desea utilizar:

Método 1: Utilizar el shortcode para incrustar (mejor para vídeos de YouTube)

Puede establecer una anchura máxima utilizando un shortcode. Este método es fácil, sobre todo si solo quieres establecer la anchura máxima para un pequeño número de entradas. También hemos comprobado que este método funciona bien para incrustar vídeos en entradas de blog de WordPress.

Sin embargo, el shortcode incrustar y sus parámetros de anchura y altura no funcionan para todos los proveedores de oEmbed. Por ejemplo, no puedes usarlo para establecer la altura y anchura de un Giphy incrustado en WordPress. En ese caso, puedes probar uno de los otros métodos que se mencionan a continuación.

En lugar de pegar la URL en el editor de entradas, tendrás que crear un bloque shortcode. A continuación, puedes añadir parámetros de anchura y altura al código incrustado.

Por ejemplo, basta con envolver lo siguiente en etiquetas incrustadas:

width="900" height="600"]https://www.youtube.com/watch?v=6LwWumPeues

Sólo tiene que cambiar los valores de anchura y altura para adaptarlos a sus necesidades y sustituir la URL por el contenido que desee incrustar.

Embed shortcode width

Cuando esté satisfecho con la página, sólo tiene que hacer clic en “Actualizar” o “Publicar”.

El contenido incrustado debería caber perfectamente en el espacio disponible.

oEmbed width adjusted

Método 2: Utilizar los bloques incrustados integrados en WordPress (Fácil)

El editor de bloques de WordPress viene con varios bloques incrustados para diferentes servicios oEmbed.

Embed blocks in WordPress

Algunos de estos bloques permiten cambiar la alineación del incrustado y establecer el contenido en ‘Ancho ancho’ o ‘Ancho completo’.

Si eliges ancho completo, entonces el bloque incrustado y el contenido incrustado ocuparán todo el ancho de la pantalla. Si eliges anchura ancha, el bloque incrustado ocupará toda la anchura, pero el contenido mantendrá el mismo tamaño.

El resultado final puede variar dependiendo de tu tema de WordPress. Sin embargo, se trata de un método rápido y sencillo, por lo que vale la pena ver si funciona para su sitio web de WordPress.

Basta con hacer clic en el botón “Alinear” de la pequeña barra de herramientas situada encima del bloque. A continuación, selecciona “Anchura amplia” o “Anchura completa”.

Adding aligning to an embed block in WordPress

Si esto corrige el problema de la anchura máxima para la incrustación, entonces usted puede seguir adelante y publicar la página. Si no estás satisfecho con el resultado, tendrás que probar otro método.

Método 3: Usar PHP personalizado (Establecer un ancho máximo para todos los incrustados)

A veces es posible que desee establecer un ancho máximo para todo el contenido incrustado. La forma más sencilla de hacerlo es añadiendo código personalizado a su sitio web WordPress.

El problema de este método es que el atributo de anchura máxima solo funcionará si el contenido incrustado no tiene ya definido un ‘width’. Si el código incrustado ya incluye su propio atributo ‘width’, es posible que este método no funcione.

Si no ha editado el código de su sitio antes, eche un vistazo a nuestra guía sobre cómo añadir fácilmente fragmentos de código personalizados en WordPress.

Algunas guías le piden que edite los archivos del tema manualmente, pero esto puede causar errores comunes de WordPress e incluso puede romper completamente su sitio web.

Por esa razón, recomendamos usar WPCode. Facilita añadir fragmentos de código en WordPress sin tener que editar los archivos de tu tema. De esta forma, puedes actualizar o cambiar tu tema sin perder todas las funciones de tu código personalizado.

En primer lugar, deberá instalar y activar el plugin gratuito WPCode. Para más información, consulte nuestra guía paso a paso sobre cómo instalar un plugin de WordPress.

Una vez activado, vaya a Fragmentos de código ” Añadir fragmento.

En la pantalla siguiente, pase el ratón por encima de la opción “Añadir su código personalizado (nuevo fragmento)” y haga clic en el botón “Usar fragmento” cuando aparezca.

Adding a code snippet to WordPress

En la siguiente pantalla, escriba un título para el fragmento de código. Esto es sólo para tu referencia, así que puedes usar lo que quieras.

A continuación, abra el menú desplegable “Tipo de código” y elija “Fragmento de código PHP”.

Adding a PHP code snippet to WordPress

Una vez hecho esto, basta con pegar lo siguiente en el editor de código:

add_filter( 'embed_defaults', 'wpbeginner_embed_defaults' );

function wpbeginner_embed_defaults() {
    return array(
        'width'  => 400,
        'height' => 280
    );
}

No olvide ajustar los atributos de altura y anchura para adaptarlos a sus necesidades.

Por último, haga clic en el carrusel / control deslizante “Inactivo” para que aparezca “Activo”. A continuación, haga clic en el botón “Guardar fragmento” o “Actualizar” para activar el fragmento de código.

Activating a custom PHP snippet

Método 4: Usar CSS (Establecer anchura máxima para tipos incrustados específicos)

Por defecto, WordPress añade automáticamente clases CSS a diferentes áreas de su sitio.

También añade varias clases CSS a los bloques incrustados. Puede utilizar estas clases CSS para establecer una anchura máxima para los bloques incrustados en su blog de WordPress.

Esta es una buena opción si desea establecer un tamaño máximo para un tipo específico de incrustado, como Tweets incrustados. También permite crear un tamaño máximo para todo el contenido incrustado, independientemente del tipo.

Para saber a qué clases CSS debes dirigirte, simplemente incrusta contenido en una entrada o página y luego visualízalo previamente en tu navegador / explorador.

A continuación, pasa el cursor por encima del contenido incrustado y haz clic con el botón derecho. En el menú que aparece, selecciona la herramienta “Inspeccionar”.

Chrome's inspect tool

Esto abre un nuevo panel que muestra todas las clases CSS que WordPress ha añadido al contenido incrustado. Puede utilizar estas clases para establecer un ancho máximo para este tipo de incrustar.

Para dirigirse a un proveedor específico de oEmbed, normalmente utilizará .wp-block-embed-providername, así que busque esta clase en el panel.

Por ejemplo, en la siguiente imagen, hemos subrayado la clase .wp-block-embed-providername. En esta línea, también podemos ver una clase . wp-block-embed-pinterest.

Finding CSS classes for embed blocks

Puedes establecer un ancho máximo para incrustar Pinterest solo usando la clase .wp-block-embed-pinterest.

Por ejemplo:

.wp-block-embed-pinterest {
    max-width: 900px!important;
}

Sólo ten en cuenta que puede que necesites reemplazar .wp-block-embed-pinterest con una clase CSS diferente, dependiendo del contenido al que quieras dirigirte.

Si desea establecer una anchura máxima para todas las incrustaciones, puede utilizar el siguiente fragmento de código:

.wp-block-embed {
    max-width: 900px!important;
}

La forma más sencilla de añadir CSS personalizado a tu sitio web es utilizando WPCode. Basta con crear un nuevo fragmento de código personalizado siguiendo el mismo proceso descrito anteriormente.

Sin embargo, esta vez abra el desplegable “Tipo de código” y seleccione “Fragmento de código CSS”.

Adding a CSS snippet to WordPress

Ahora puede guardar y publicar este fragmento de código exactamente de la misma forma que lo hace con cualquier fragmento de código WPCode.

Una vez hecho esto, WordPress utilizará este valor como tamaño máximo para sus incrustaciones.

Sugerencia adicional: Cómo añadir fácilmente sus feeds de medios sociales a WordPress

Si incrustas regularmente contenido de plataformas de medios sociales, puedes ahorrar mucho tiempo y esfuerzo utilizando Smash Balloon.

Smash Balloon es el mejor plugin de medios sociales para WordPress y le permite añadir fácilmente sus feeds de medios sociales a un sitio web de WordPress.

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

Es compatible con todos los medios sociales populares incrustados, incluidos YouTube, Twitter e Instagram.

Y lo que es más importante, Smash Balloon es adaptable a dispositivos móviles y funciona con cualquier tema de WordPress, por lo que el contenido incrustado siempre tendrá un aspecto estupendo.

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

Esperamos que este artículo te haya ayudado a aprender cómo establecer el ancho máximo de oEmbed en WordPress. Puede que también quieras ver nuestra completa hoja de trucos sobre medios sociales o nuestra comparativa de expertos sobre el mejor software de chat en vivo para pequeñas empresas.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Descargo: Nuestro contenido está apoyado por los lectores. Esto significa que si hace clic en algunos de nuestros enlaces, podemos ganar una comisión. Vea cómo se financia WPBeginner , por qué es importante, y cómo puede apoyarnos. Aquí está nuestro proceso editorial .

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.

El último kit de herramientas de WordPress

Obtenga acceso GRATUITO a nuestro kit de herramientas - una colección de productos y recursos relacionados con WordPress que todo profesional debería tener!

Reader Interactions

44 comentariosDeja una respuesta

  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.

      Administrador

  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.

      Administrador

Deja tu comentario

Gracias por elegir dejar un comentario. Tenga en cuenta que todos los comentarios son moderados de acuerdo con nuestros política de comentarios, y su dirección de correo electrónico NO será publicada. Por favor, NO utilice palabras clave en el campo de nombre. Tengamos una conversación personal y significativa.