¿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.
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.
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.
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.
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.
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.
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.
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”.
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.
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.
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:
- Los mejores consejos y tutoriales de Facebook para usuarios de WordPress
- Cómo publicar automáticamente en Facebook desde WordPress
- Cómo instalar y configurar los comentarios de Facebook en WordPress
- Cómo crear un feed de Facebook personalizado en WordPress
- Cómo mostrar las valoraciones de tu página de Facebook en WordPress
- Cómo corregir el problema de la miniatura incorrecta de Facebook en WordPress
- Cómo mostrar Twitter y Facebook del autor en la página de perfil
- Cómo crear una página de destino de Facebook Ads en WordPress
- Cómo corregir el problema de oEmbed de Facebook e Instagram 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.
Daniel
This is indeed helpful but SEO Yoast’s interface doesn’t look like this anymore. This needs updating.
WPBeginner Support
Thank you for letting us know that their interface has been updated, we will look to update it when we update the article
Administrador
Jiří Vaněk
Thanks for the tutorial. I’ve been adding Open Graph in AIO SEO and I’m still surprised that AIO SEO tells me there isn’t one. I spent about half an hour on this before I found out that I had to click refresh again in the SEO evaluation so that the plugin would download the new WordPress settings and do a new SEO analysis. Such a simple thing and it took me so long.
Harry Goldhagen
Hello, thanks for the code snippet, I look forward to trying it. One question, will it then allow FB to pick up the featured image (is that the “thumbnail”?) and excerpt for each blog post, or will it just use the sitewide logo image designated in line 19? I’ve tried Blog2Social, but the posts lacked the featured image and excerpt and did not look good. Thanks!
WPBeginner Support
The code snippet should set your featured image to the featured image of the post.
Administrador
Kiss Attila
Hi,
Awesome code. BUT, why it’s not changes og:url and og:image. I tried with a post with no image set as default. But checking it on fb debugger, it picks up my logo from the footer instead of getting the image I added in the og:image part.
Title is working it changed from the origin and I pasted og:description too. All the most important metas but image and url.
Why is that?
Thanks,
Atila
WPBeginner Support
Please ensure you’ve cleared any caching on your WordPress site as that is the most common reason it would not update to match the code.
Administrador
rehman
hi how can i modify the code to add OG tags for custom post types i tried by changing this line code if ( !is_singular()) to if ( is_singluar( array( ‘post’, ‘publications’) ) ) but my website throw fatal error. can anyone please help thank you
WPBeginner Support
You should not need to modify the code to work with custom post types and it should work on them
Administrador
gabriele biagini
Hello, i tried all the solution suggested still i miss some parameter to the schema:
A required field is missing: id
A required field is missing: price
A required field is missing: availability
Is there any solution via plugin or updating the function.php code?
WPBeginner Support
That would be markup for a product you are selling on your site and All in One SEO does have the option to add that markup to your products.
Administrador
Richard S.
Wow, this really worked for me, you’re awesome!
WPBeginner Support
Glad our guide was helpful
Administrador
evelien
You did it again – looking for a solution, and you deliver ! You rule
WPBeginner Support
Glad our guide was helpful
Administrador
Eddie
Does this also work for sms text message url previews or just Facebook?
WPBeginner Support
While not specifically for SMS messages, the markup helps with that as well.
Administrador
Indranil Paul
If I use the Yoast SEO settings, will it take times for showing the perfect result in facebook share? Or will it start working within minutes?
WPBeginner Support
That would depend on your site’s caching and any caching on Facebook for how long it takes
Administrador
Indranil Paul
I’m facing this problem in all social sharing sites.
WPBeginner Support
If it is not showing what you set on every social site, you would want to reach out to Yoast’s support and let them know to ensure there isn’t a problem with the plugin.
Udaya Bhaskar
Hello
When I share my post in facebook it’s how my post featured image .
But when I share in whatsapp it’s not show my featured image with link please help me..
WPBeginner Support
If you’re using Yoast to add the meta data, we would first recommend reaching out to Yoast to ensure that there aren’t any known issues.
Administrador
Colin
My title looks like this in the preview:
%%title%% %%page%% %%sep%% %%sitename%%
How do I fix this?
Pramod Singh
Hello please help me
Facebook has blocked my site, now in the Facebook developer app, I can not even link my site because it has blocked the Facebook
Please tell me how to unblock your website with Facebook
Sadie
Hello
Please can you advise when using a child theme – do i need to copy the parent theme functions.php and then add the above script to a newly created functions.php and upload it to the child theme folder OR do I just add the script to the parent theme functions.php
Thanks for reading Sadie
WPBeginner Support
Hi Sadie,
You can add it to either functions.php file.
Administrador
Max
How would I remove the “By …” from appearing on the card?
Currently we have an issue where it displays as: site-name | By site-name
We just want the first website name to appear and not twice.
Laura
I’m using this on a self-hosted website. What do I do about the USER ID that I’m supposed to replace since the site is not on wordpress.com?
Suraj
Hello,
I have a big problem!!
When I share my post in facebook it’s how my post featured image .
But when I share in whatsapp it’s not show my featured image with link please help me..
Malik Adil
All Good, But still one problem, How to add Facebook ID..After using this code, following Facebook ID message appears.
The ‘fb:app_id’ property should be explicitly provided, Specify the app ID so that stories shared to Facebook will be properly attributed to the app. Alternatively, app_id can be set in url when open the share dialog.
Eric Hepperle
I enjoyed this article, but in January 2018 this *manual code* option doesn’t appear to work completely. For instance, though I have verified that the default image property works, when I create a new post, I don’t see ANYWHERE a field where one can begin to edit “open graph (og)” metadata.
Suggestions? Thanks!
Mahesh Yadav
Thanks for such great information. But I have one question.
How helpful it is to add facebook graph meta data in our site..?
And if it is very much helpful, for what purpose, it is helpful..?
elsa
This plugin gave me a white screen of death, obviously a conflict with something or memory exceeded
Jin Miller
What if I am wanting to change the thumbnail image not for the whole site, but just a page off my wordpress site : For example I’m trying to share an event page from my site and would like a unique, relevant thumbnail. Help?
Nikki
Hi Jin, Did you ever get an answer to your question? I’m looking for the same information.
Thank yoU!
Vic
Hey, I wanted to include Worpress SEO by Yoast but Im not sure if latest version is compatible with my version of Worpress (4.2.2) do you know if is safe to activate?
Thanks guys
Martin
Does my Facebook profile have to be public in order for my Facebook User ID to be good to use here?
Martin
I’ve added the code for manually adding this to my theme. However, things aren’t working. Does my profile have to be public in order for my Facebook user id to be accessible?
WPBeginner Support
Hi Martin,
Yes it would work.
Administrador
Jordan Carter
Is this still valid for today? I tried it and works, but I noticed in the code the following: “xmlns:fb=”http://www.facebook.com/2008/fbml”‘;
Isn’t 2008 a little old? Is there a newer protocol we should be using today?
Wagner Lungov
Hello, thanks for posting. I remained with one doubt. I understood that the in each post is dynamically constructed by the functions you explained so well. What I can’t figure out is where the variables called by that function are defined and stored. When you put property=”og:type” content=”article”/, OK you are defining with a fixed string. But when you use: property=”og:title” content=”‘ . get_the_title() . ‘”, where is the function get_the_title() going to get it? How can I define before hand those values for each post in a way that the code will pick the right meta data for each parameter?
Jordan Carter
get_the_title() will get your post title. If you want to use something else, you could always get the value from a meta box. With the advanced custom fields plugin, it would be something like get_field(“my_field”), or with a regular WordPress custom meta field it would be get_post_meta($post->ID, “my_field”, true). See get_post_meta()
Jolanda
Nicely explained! I try to figure out where I can add the code in checking the size of the featured image, since FB needs a size with a minimum of 200px for both width and height, otherwise it will use another image from the post.
Any help would be great!
Mohsin Rafique
Nicely explained & works like a charm.
Devyn
I’ve been trying to use Yoast to enable my meta data so I can use Rich Pins on Pinterest. I’ve done what this tutorial says, but Pinterest still won’t recognize my post. Is there another plugin I could try?
Michelle
I added the Yoast plugin and there is no social option. Please help me. I am at my wits end with this issue.
Brent Watkins
Same problem here.
Glenford
Once you have Yoast installed the look under SEO » Dashboard » Titles & Metas and under that is Social.
in Social you should Enable the “Add Open Graph meta data” in the Facebook tab.
Xavier
This option just isn’t there with v4.6 of the plugin.
Under SEO >> Dashboard, the tabs I have are: Dashboard, General, Features, Company info, Webmaster tools and Security. No mention of Titles & Metas or Social.
Is this because I haven’t set up a Facebook social profile? Surely this shouldn’t be needed just to be able to configure OG stuff!
WPBeginner Support
Hey Xavier,
First you would need to go to SEO » Features page and then click ‘Enable’ under ‘Show Advanced Settings Pages’ option. This will display advanced settings pages in Yoast SEO. For more details see our article on how to install and setup Yoast SEO.
joe Barrett
I added social sharing to the search result template, so each excerpt has a share button BUT the meta data that is shared is messed up and uncontrollable with this, is there a way to make this work better when there are 20 reuslts on the same page with different meta description for each?
giovanna
Hi can you help me please? I added the code in function and what I have to add in the head please?
benjamin s
Here’s also a nice improvement to make an exception for the home-page:
if (is_front_page()){
echo ”;
echo ”;
echo ”;
}else{
echo ”;
echo ”;
}
benjamin
I just want to say thanks! … this is very helpful, you the best!
WPBeginner Support
Glad you found it helpful. Don’t forget to follow us on Facebook for more WordPress tips and tutorials.
Administrador
Laura K
I’ve downloaded the Yoast plugin, and set it up for my home page, but when I enter the website on Facebook it still won’t show the image I’ve specified, or the text snippet I’ve written.
Also can’t find my Facebook URL using the link you provided, it just gives me an error…
I tried debug but it says Facebook pages can’t be debugged, and they have no cache.
Sooooo….nothing has worked so far!
WPBeginner Support
You need to enter your WordPress site URL in the debug tool.
Administrador
Courtney
Hi there,
I have SEO Yoast and I uploaded the new image and its still not working on facebook……???
MassimoDIFA
Thank you, manually added open graph on header, perfect!! Thank you!!
D
I just wanted to thank you for this very thorough description on the process of connecting facebook to your wordpress page. I’ve been trying to do for days now following other sites and recommendations. This evening I came across your page from a google search and bam, it worked. Hooray! Thanks a lot.
Amanda Paul
Thanks for this info. It was really easy to follow. I uploaded the Yoast plugin and followed all the steps and saved but the thumbnail is still just a blank box. does it take some time to flow through? Do I need to log out and back in again to Facebook? or Wordpress?
Mahmud Ayaz
Hi! When i replace this link with my name http://graph.facebook.com/syedbalkhi got this error
{
“error”: {
“message”: “(#803) Cannot query users by their username (mahm0od)”,
“type”: “OAuthException”,
“code”: 803
}
}
Any Solution?
Daniele Besana
Hi guys, I’m having problems with og:description, basically all the formatting is missing on the shared page. New lines are not respected, how can I control that?
Thanks!
JC
I have the same problem, also getting og:description missing
amelliya
me too – any help?
AC
I have the same problem, and I cannot use FB debugger because i work in localhost…
Marc
this worked for me:
$metadesc = strip_tags(get_post_field(‘post_content’, $post->ID));
echo ”;
(my posts had a very short content)
Kim McCann
The following works by pulling from your excerpt. Just add under og:title
WPBeginner Staff
Check your page using Facebook debug tool
https://developers.facebook.com/tools/debug Usually checking a page with the debug tool refreshes the Facebook’s cache and you will be able to see the new image.
BK
Thank you for taking the time to reply. Will give it a shot!
BK
Thanks for this. I want to share link directly from my site using the social button. However, when I click on for example the Facebook share button, the image and the description is still using a previous information. Although I have updated the image and description using Yoast SEO and specifically customise the image and description for that post. May I know what did I do wrongly?
Naren Patel
Thank you very much, I really want this information.
Robin
Thank you. I can’t tell you how long I have been trying to figure this out. Easy to do with ZiPLIST for recipes but could not figure it out for Articles.
Maria
Hi! I have a issue that i don’t know how to solve. When I try to share a link on facebook from my blog, or a particular page this message appera “page not found” or the link with symbols I don’t understand. I controlled th elinks with object debugger and this is what appear: required property ‘og:title’ of type ‘string’ was not provided. How can I solve it, please?
Salih Kulangara
@ Syed Balkhi. —– Just want to ask you this, After all I have got setup all the tags, and got a clean debug test result without any warning, when any one click on the Facebook Like button i used in my web page, it’s not showing up in the Facebook Timeline feed, just showing up in the recent activity section only, why is this, Is there anything else I have to add to get it be shown in the newsfeed directly when the click the LIKE button??????
Anas Khan
Great tutorial, i want to know is there any tutorial about open graph meta for Google Plus ?