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 añadir metadatos Open Graph de Facebook en temas de WordPress

¿Quieres asegurarte de que el contenido de tu sitio web en WordPress se vea bien en Facebook? Tienes que añadir los metadatos Open Graph de Facebook a tu tema de WordPress.

Los metadatos Open Graph proporcionan a Facebook y a otros sitios de medios sociales información acerca de tus entradas y páginas de WordPress, y te permiten controlar cómo se ven cuando alguien las comparte.

En este artículo, te mostraremos cómo añadir fácilmente los metadatos Open Graph de Facebook en temas de WordPress. Compartiremos tres métodos diferentes, incluido el método All in One SEO que utilizamos en WPBeginner, para que puedas elegir el que mejor se adapte a tu sitio web de WordPress.

How to Add Facebook Open Graph Meta Data in WordPress Themes

Puede enlazar directamente con el método que más le interese:

Método 1: Añadir metadatos Open Graph de Facebook con AIOSEO

All in One SEO es un popular plugin SEO para WordPress utilizado por más de 3 millones de sitios web. Le permite optimizar fácilmente su sitio web para los motores de búsqueda, así como plataformas sociales como Facebook y Twitter.

En primer lugar, debe instalar y activar el plugin gratuito All in One SEO. Para más detalles, consulta nuestra guía paso a paso sobre cómo instalar un plugin de WordPress.

Una vez activado, tienes que visitar la página All in One SEO ” Redes Sociales. Aquí, puede introducir la URL de su página de Facebook y todas sus otras redes sociales.

The AIOSEO SEO plugin for WordPress

A continuación, haz clic en la pestaña Facebook de la parte superior de la página y verás que Open Graph Markup está activado por defecto.

Puedes hacer clic en el botón “Subir o seleccionar imagen” para elegir una imagen por defecto de Facebook OG si un artículo no tiene una imagen de Open Graph.

Set default Open Graph image

Si se desplaza hacia abajo, podrá personalizar el nombre de su sitio, la descripción y otros ajustes. No olvides hacer clic en el botón azul “Guardar cambios” cuando hayas terminado.

Ahora que ha establecido los metatags de Open Graph para todo el sitio, el siguiente paso es añadir metadatos de Open Graph para entradas y páginas individuales.

Por defecto, AIOSEO utilizará el título y la descripción de tu entrada para el título y la descripción de Open Graph. También puedes establecer manualmente la miniatura de Facebook para cada página y entrada.

Simplemente edita la entrada o página y desplázate hasta la sección “Ajustes de AIOSEO” debajo del editor. Desde aquí, cambia a la pestaña Social y verás una vista previa de tu miniatura.

AIOSEO Facebook preview

Aquí puedes establecer la imagen de los medios sociales, así como el título y la descripción.

Desplácese hasta el campo “Fuente de la imagen”. Puede elegir utilizar la imagen destacada, subir una imagen personalizada u otras opciones.

Choose which WordPress image to use as your Facebook thumbnail

Método 2: Establecer los metadatos Open Graph de Facebook con Yoast SEO

Yoast SEO es otro plugin SEO para WordPress que puedes utilizar para añadir metadatos Open Graph de Facebook a cualquier sitio WordPress.

Lo primero que tienes que hacer es instalar y activar el plugin Yoast SEO. Para más detalles, consulta nuestra guía paso a paso sobre cómo instalar un plugin de WordPress.

Una vez activados, los datos de Open Graph de Facebook están activados por defecto.

Puedes comprobarlo yendo a Yoast SEO ” Ajustes y desplazándote hacia abajo hasta la sección Compartir en redes sociales. Ahora puedes asegurarte de que la característica de datos Open Graph está activada / activa.

Enable Facebook Open Graph

debe ir a SEO ” Social y seleccionar la opción “Activado” en “Añadir metadatos de Open Graph”.

Puedes guardar tus ajustes o continuar y configurar otras opciones sociales de Facebook.

Puedes proporcionar un ID de aplicación de Facebook si utilizas uno para tu página de Facebook e insights. También puedes cambiar el meta title, la meta description y la imagen de Open Graph de tu página de inicio.

Por último, puede establecer una imagen por defecto que se utilizará cuando no se haya establecido ninguna imagen para una entrada o página.

La versión Premium de Yoast SEO también te permite establecer metadatos Open Graph para entradas y páginas individuales. Solo tienes que editar una entrada o página y desplazarte hasta la sección “Yoast SEO” situada debajo del editor.

Set open graph meta data for post and pages using Yoast

Desde aquí, puedes establecer una miniatura de Facebook para esa entrada o página en particular. Si no estableces el título o la descripción de la entrada, el plugin utilizará tu meta title y description de SEO.

Ahora puedes guardar tu entrada o página, y el plugin almacenará tus metadatos Open Graph de Facebook.

Método 3: Añadir metadatos Open Graph de Facebook mediante código

Este método normalmente requiere que copies y pegues código en el archivo functions.php de tu tema. Sin embargo, recomendamos añadir el código utilizando el plugin WPCode, que hace que sea más fácil y seguro añadir código personalizado en WordPress.

WPCode también viene con una biblioteca de fragmentos de código listos para usar, incluido uno para añadir etiquetas básicas de Open Graph, por lo que solo se necesitan un par de clics.

Primero, instala y activa el plugin gratuito WPCode. Para más detalles, consulta nuestra guía sobre cómo instalar un plugin de WordPress.

Una vez activado, puede ir a Fragmentos de código ” + Añadir fragmento desde su escritorio de WordPress.

Busca el fragmento de código “Añadir etiquetas básicas de Open Graph” en la biblioteca. Cuando lo encuentres, pasa el cursor por encima y haz clic en el botón “Usar fragmento de código”.

Select the 'Add basic Open Graph Tags' snippet from the library

Entonces, WPCode añadirá automáticamente el código por ti, así como establecerá la cabecera de todo el sitio como ubicación del método de inserción.

WPCode automatically adds the code for Open Graph data

Después, todo lo que tienes que hacer es conmutar el fragmento de código a “Activo” y hacer clic en el botón “Actualizar”. Tu tema empezará a mostrar los metadatos de Facebook Open Graph en la cabecera de WordPress.

Activate and update snippet

Si eres un usuario avanzado, puedes copiar y pegar el código siguiente en el archivo functions.php de tu tema.

Dado que esto requiere que edite directamente los archivos de su tema, asegúrese de hacer una copia de seguridad de los archivos de su tema antes de realizar cualquier cambio.

//Adding the Open Graph in the Language Attributes
function add_opengraph_doctype( $output ) {
        return $output . ' xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml"';
    }
add_filter('language_attributes', 'add_opengraph_doctype');
 
//Lets add Open Graph Meta Info
 
function insert_fb_in_head() {
    global $post;
    if ( !is_singular()) //if it is not a post or a page
        return;
        echo '<meta property="fb:app_id" content="Your Facebook App ID" />';
        echo '<meta property="og:title" content="' . get_the_title() . '"/>';
        echo '<meta property="og:type" content="article"/>';
        echo '<meta property="og:url" content="' . get_permalink() . '"/>';
        echo '<meta property="og:site_name" content="Your Site Name Goes Here"/>';
    if(!has_post_thumbnail( $post->ID )) { //the post does not have featured image, use a default image
        $default_image="http://example.com/image.jpg"; //replace this with a default image on your server or an image in your media library
        echo '<meta property="og:image" content="' . $default_image . '"/>';
    }
    else{
        $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
        echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
    }
    echo "
";
}
add_action( 'wp_head', 'insert_fb_in_head', 5 );

Recuerde añadir el nombre de su sitio en la línea 17, donde dice “El nombre de su sitio va aquí”. A continuación, cambie la URL de imagen por defecto en la línea 19 por una de sus propias URL de imagen.

Te recomendamos que pongas una imagen con tu logo ahí, de modo que si tu entrada no tiene miniatura, entonces tire del logo de tu sitio.

También tienes que añadir tu propio ID de aplicación de Facebook en la línea 13. Si no tienes una aplicación de Facebook, puedes eliminar la línea 13 del código.

Guías de expertos sobre Facebook y WordPress

Ahora que ya sabes cómo añadir los metadatos Open Graph de Facebook, puede que te interese ver otras guías relacionadas con el uso de Facebook en WordPress:

Esperamos que este artículo te haya ayudado a añadir los metadatos Open Graph de Facebook en WordPress. También puedes consultar nuestra guía sobre cómo organizar un sorteo o concurso en WordPress o nuestra selección de los mejores plugins de Facebook para hacer crecer tu blog.

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

221 comentariosDeja una respuesta

  1. WPBeginner Staff

    Did you set a featured image? did you replace the default image URL in the code with your own image URL?

  2. Ikix

    Hello, I’ve tried everything i could an i can’t display thumbnail image when i post my blog url on facebook, i already add the code as you said, i download tons of plugings and there is no image in facebook! can you help me please? pleeease!

  3. Jason C.

    what about just for a single image to be added to the thumbnail options in Facebook? I’ve noticed it picks up my featured image no problem, but doesn’t pick up the others in the post. Is there a way to manually add them with some quick code?

  4. WPBeginner Staff

    Sorry the plugin is no longer available. We have updated the article, with new information. Hope this will help you add Facebook Open Graph Meta Data into your WordPress. site.

  5. M

    its still pulling the image from the sidebar instead of the image i have put in the functions file?

  6. damian

    What about og:description?

  7. Musadiq

    Hi,

    How can I include a facebook in the code above? So it can directly publish an article to our profile timeline and also to our facebook page. Thank you

  8. Hassan

    its not working for me when i share my posts on face book its only shows my last instagram pics

  9. Loes Liemburg

    Hi, I installed this plug-in, but can’t see the OG-options in my settings menu. I’ve refreshed and waited, but still nothing. What has gone wrong?

  10. Manuel Gomez

    This line means that the image will use the medium size?

    $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), ‘medium’ );

    If i replace for “big” will use the big image? i would like to see the link post with the new format in facebook, because i can get more clics.

    Thanks!

  11. Alexandra

    Thank you! the code worked perfectly!

    • M

      Unfortunately this did not work for me, I can’t even see it being output in the WP head source code. I’m using the code method as I don’t want to add any plugins to the site.

      I’ve checked the htaccess file and that is not causing any issues since it’s blank except for the perma link declaration.

      Its also not a caching plugin either since I dont have one in place. Any ideas?

      • M

        Actually sorry this did work, but unfortunately using the debugger tool it still seems that posting a link on my timeline still does not show the og:image.

        Even if it’s there in the json. Its really bizarre. The debugger shows the post but without any image in the share preview. Any ideas anyone?

  12. Attila

    Hello Syed,
    I have use many plugins to extract my graph meta info since I’ve started to use Wordpress and Facebook and I can say that “Facebook Open Graph Meta for WordPress” is the most simple yet professional plugin so far.

    I have a minor issue tough…when debugging my posts link with the the Facebook debugger, my Raw Open Graph Document Information does not show up properly. I have special characters included as my content is in Hungarian language.

    Here is an example:
    Meta Tag:

    I would appreciate if someone could tell me how to fix this.

    Thanks in advance and keep up the good work.

    Best Regards

    • JessDelAngel

      HI!

      Did you find a solution for this?

      Regards

  13. Jim

    Works well – thanks. This is still the best way to integrate without a plugin, yes?

  14. ally

    I’ve been using this code for a long time but recently there’s been problems, it doesn’t always pull the image. I used the linter and found this errror:

    Inferred Property The ‘og:description’ property should be explicitly provided, even if a value can be inferred from other tags.

    So I added the description tag and that seems to have resolved the image issue but now it no longer displays the article content.

    Any idea’s how to resolve this? I just need to show the first few lines of content.

    Thanks

      • Goob

        Yoast’s SEO Plugin doesn’t seem to have single page og:descriptions built-in.

        • Editorial Staff

          Yes it does have it built-in. By default it pulls your meta description, but it also has the option for you to modify the description from the Yoast SEO meta box.

  15. Theo

    Hi there,

    I was just wondering whether it is possible to have a different “og:type” for a post and a page. As it stands (well from what I understand) is that for everything in Wordpress, this sets the “og:type” to article.

    What if I want to set “og:type” of page to say “website” and for a post “article”?

    Any suggestions or help much appreciated :)

    Thanks

  16. seitanist

    Can someone explain why

    global $post;

    is needed and where it falls in the generated code?

    • wpbeginner

      @seitanist Yes the reason why global $post is added because this code is being added outside the Loop in the section of the page. In order to pull the right information, we must call global $post which makes all those tags work.

  17. seitanist

    This worked great! Thanks!!!

  18. Editorial Staff

    You can try disabling the social feature in Yoast’s plugin and download Otto’s Simple Facebook Connect plugin. Just activate it and the base would take care of it.

    Administrador

  19. Cno

    Hello, everything worked! When i put the link of my specific blog post on my facebook wall, I have the right thumbnail, description and site name. But the post on facebook also automatically shows the complete url of my site (right under the blog title). Instead I want it to show the permalink of the specific blog post – not the url of my site. This way i can integrate the ‘likes’ for that particular post in wordpress. Please! Anyone?

  20. StephanePerez

    Hi, i tried to insall the plugin but can’t activate it because of a fatal error : Cannot redeclare add_opengraph_doctype()…/fbogmeta.php on line 24

    What i’m supposed to do?

    Thanks!

  21. techhogger

    Hi pasted this codes as per the instruction on my blog techhogger.com but still issue does not seem to resolve. I can see my adsense codes in the description area. Kindly help.

    • waqaslone

      @techhogger same problem with…let me know if u find any solution.

      • wpbeginner

        @waqaslone@techhogger For the description to appear, you have to use the excerpts. Alternatively, you can use Otto’s Simple Facebook Connect plugin and just turn the Base on. That would take care of everything for you.

        • techhogger

          @wpbeginner@waqaslone@techhogger

          I did everything. Even tried the plugin you said. Just try to share any post from my blog and you will know what exactly is happening. To some extend I was able to remove codes appearing from the description section. But now I can’t see description and thumbails of the post while sharing it on fb. Will be thankful if I get your help.

        • wpbeginner

          @techhogger@waqaslone We are using the method shared on this page on our own website. Everything works. We are using SFC on List25 and it works perfectly fine. Not sure why you are having these issues. SFC has a very smart way to parse through your content and pull out description. So I know for a fact that it pulls out description. It also pulls out all images. This most likely means that there is another plugin that is interfering on your site.Do you have a WP plugin to add the like box or the like button? or any other FB plugin?

        • techhogger

          @wpbeginner@waqaslone I tried to share again after your last reply. And the same happens. I can see only post title with description as my blog’s description instead of post description and no thumbnail. I am using Digg Digg plugin for social sharing .

        • wpbeginner

          @techhogger@waqaslone Please turn on Otto’s Simple Facebook Connect plugin. Remove the code that you have added in your functions.php …

        • techhogger

          @wpbeginner@waqaslone I think its working now. I downloaded and configured the plugin again. And now it seems to be working. Can you have a look and let me know if everything is fine now.

  22. ChristopherJosephDowney

    I am used to putting meta tags in the HTML on Blogger. Switching to Wordpress has been a headache in this aspect, as I have no HTML to edit and am not used to CSS. This plug-in is a dream, but it doesn’t seem to be working correctly. My question is this: It appears I have 3 different ID’s: My facebook profile, my facebook fan page (the one my blog links to) and my OG debugger ID that appears on the developer debugger page; which ID do I need to use for the plug-in? No matter which one I put in the plug-in when I click “debug” the thumbnail does not update and is always one of the advertisement’s gif’s. Can I have more than one default thumbnail like I would using megatags in HTML?

  23. RobKara

    When a user hits my wordpress page “object” then how do i get the facebook userid if its a facebook user viewing the page? Does facebook send a signed_request or facebook userid via the querystring?

    • wpbeginner

      @RobKara This question should be asked in the Open Graph forum because it is beyond the scope of this article.

  24. MetalPhil

    So I installed this stuff on my website (AngryMetalGuy.com) and it doesn’t work. I have *no* clue why. I am beyond frustrated and super confused. If you could please, please, please, please, pleeeease help me that would be awesome.

  25. lizbizz

    This solved my problem for the Share on Facebook button, but now when I try to share a post from my site to Facebook using Hootsuite’s Hootlet, the description text box is empty. It shows the correct thumbnail and URL but no article preview text. It worked before and still works for other sites, so I think it happened when I installed the plugin…help?

  26. SaijoGeorge

    @wpbeginner Facepalm … Thanks for the quick replay mate :)

  27. wpbeginner

    @SaijoGeorge It will only output your post’s defined excerpt. If you don’t specify an excerpt, then nothing will be displayed.

  28. SaijoGeorge

    Great plugin .. the only issue I seem to be having is that the meta property=”og:description” spits out some random data :( . Thr url for a sample post is 1800pocketpc.com/watch-out-for-windows-phone-7/22453/ similar issue on another blog bestwp7games.com/crazy-horses-match-maker-a-path-drawing-game.html ( here og:description comes out to be blank ) I am using thesis variations on both of those sites .. was wondering if any of you guys have come across this issue

    It’s also worth noting that meta description tag on those pages seems to ouput the right data

  29. wpbeginner

    @CarlosDeGuzman It takes a while for the linter to update.

  30. CarlosDeGuzman

    Hi wpbeginner! I installed the plugin on my site, ww w.swimbikerun.ph and it’s not working. I’m still getting these errors on the linter. Also no thumbnails are showing when you share a post on fb. Hope you can help :)

    Also its not showing the description

    Warning

    Required Property Missingog:title is required

    Required Property Missingog:type is required

    Required Property Missingog:url is required

    Required Property Missingog:image is required

  31. wpbeginner

    @ReyCalantaol It has nothing to do with SEO…. the Open Graph data is for Facebook…..

  32. wpbeginner

    @arabsciences@Tia Peterson You have to add the Meta Description and our plugin does that for you…

  33. wpbeginner

    @arabsciences@Tia Peterson You have to add the Meta Description and our plugin does that for you…

  34. wpbeginner

    @Tia Peterson Yes, you would need to re-install through the repository.

  35. wpbeginner

    @Tia Peterson Yes, you would need to re-install through the repository.

  36. arabsciences

    Hi

    How do pull description from aal in one seo plugin.?

    it it not working for me

  37. arabsciences

    @Tia Peterson@wpbeginner

    I use All in one seo plugin and could not pull the description to show in url linter

  38. arabsciences

    @Tia Peterson@wpbeginner

    I found a fix for that which shows first 300 characters of the post.

    just change og:description to :

    <meta property=”og:description” content=”<?php echo strip_tags(get_the_excerpt($post->ID)); ?>” />

  39. ClyoBeck

    Okay, I’ve gone back to the original theme files and uploaded the original functions.php file. No go. Still a blank screen. I’m thinking up upgrading the theme to see if that will help. I’m wondering if the code I put in the functions.php file, somehow, changed something else. Is that possible?

  40. wpbeginner

    @ClyoBeck Make sure that there are no extra spaces at the bottom of the functions.php file …

  41. ClyoBeck

    Hi guys,

    I should have just downloaded the plug-in. Instead I copied and pasted the code above into my functions.php file and now my blog has disappeared.

    I went into my server and, having made copies of the php file in notepad, uploaded the old file. Still no luck.

    Looks like I’m going to have to hire a programmer to fix this.

    Any advice?

  42. Livefyre

    @wpbeginner Thanks. I don’t think I got the update, though. Should I just download the plugin again from the WP plugin repository and re-install?

  43. wpbeginner

    @Tia Peterson Just uploaded the fix for this and another issue. It should be live within 15 minutes or sooner (whenever the SVN updates go through).

  44. wpbeginner

    @SteveJoseph@joshuatj Also with the linter (not sure exactly what the number is) but if your post has that many likes, then it won’t reset the description / title and such… If I am correct, then that number is not very high…

  45. SteveJoseph

    @wpbeginner@joshuatj Thanks for the response wpbeginner. I tried your plugin within the last 3 days so was fairly certain it was the latest version but that didn’t seem to work for me. I’m going to go with your suggestion that it will fix itself but the current solution is not the most ideal. It’s pulling the description from my blog “intro” section which is helpful in telling the audience about me but does very little to support why they should click on the article or shared item. Thankfully it does show the correct image and post headline just not the description from the post itself.

    Since Facebook hyped open graph so much you’d like to have imagined they would have made sure this was working and buttoned up pretty solid. Thanks again.

  46. Tia Peterson

    Hi! For some reason, the plugin doesn’t pull a description. At first, I figured out that it was pulling the description from the ‘excerpt’ field, so I started using that field every time. Now, it doesn’t even pull from that. Not sure why. I am using the latest version of the plugin, StudioPress News Child Theme for Genesis, and Wordpress version 3.1.

    Here is our most recent post to show you that when you paste this URL into Facebook, only the image and title show up. In the source code, the description field for the open graph plugin is completely empty. http://www.bizchickblogs.com/2011/08/what-do-you-know-about-naturopathy.html

    Thanks for your help!

  47. wpbeginner

    @SteveJoseph Facebook takes a bit long to update older posts, but it will fix itself.

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.