Quer ter certeza de que o conteúdo do seu site WordPress ficará ótimo no Facebook? Você precisa adicionar os metadados do Facebook Open Graph ao seu tema do WordPress.
Os metadados do Open Graph informam ao Facebook e a outros sites de mídia social informações sobre seus posts e páginas do WordPress e permitem que você controle a aparência deles quando alguém os compartilha.
Neste artigo, mostraremos a você como adicionar facilmente metadados do Facebook Open Graph em temas do WordPress. Compartilharemos três métodos diferentes, incluindo o método All in One SEO que usamos na WPBeginner, para que você possa escolher o que funciona melhor para seu site WordPress.
Você pode usar os links rápidos abaixo para ir direto ao método que mais lhe interessa:
Método 1: Adicionar metadados do Facebook Open Graph com o AIOSEO
OAll in One SEO é um popular plugin de SEO para WordPress usado por mais de 3 milhões de sites. Ele permite que você otimize facilmente seu site para mecanismos de pesquisa, bem como para plataformas sociais como Facebook e Twitter.
Primeiro, você precisa instalar e ativar o plug-in gratuito All in One SEO. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.
Após a ativação, você precisa visitar a página All in One SEO ” Social Networks (Redes sociais ). Aqui, você pode inserir o URL da sua página do Facebook e de todas as suas outras redes sociais.
Em seguida, clique na guia Facebook, na parte superior da página, e você verá que a marcação do Open Graph está ativada por padrão.
Você pode clicar no botão “Carregar ou selecionar imagem” para escolher uma imagem padrão do Facebook OG se um artigo não tiver uma imagem do Open Graph.
Se você rolar a tela para baixo, poderá personalizar o nome do site, a descrição e outras configurações. Não se esqueça de clicar no botão azul “Salvar alterações” quando terminar.
Agora que você definiu metatags do Open Graph em todo o site, a próxima etapa é adicionar metadados do Open Graph para posts e páginas individuais.
Por padrão, o AIOSEO usará o título e a descrição de sua postagem para o título e a descrição do Open Graph. Você também pode definir manualmente a miniatura do Facebook para cada página e publicação.
Basta editar o post ou a página e rolar para baixo até a seção “Configurações do AIOSEO”, abaixo do editor. A partir daí, alterne para a guia Social e você verá uma visualização da miniatura.
Você pode definir a imagem da mídia social aqui, bem como o título e a descrição.
Basta rolar a tela para baixo até o campo “Image Source”. Você pode optar por usar a imagem em destaque, carregar uma imagem personalizada ou outras opções.
Método 2: Definir metadados do Facebook Open Graph usando o Yoast SEO
OYoast SEO é outro plug-in de SEO para WordPress que você pode usar para adicionar metadados do Facebook Open Graph a qualquer site do WordPress.
A primeira coisa que você precisa fazer é instalar e ativar o plug-in Yoast SEO. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.
Uma vez ativados, os dados do Facebook Open Graph são ativados por padrão.
Você pode verificar isso acessando Yoast SEO ” Configurações e rolando para baixo até a seção Compartilhamento social. Agora você pode garantir que o recurso de dados do Open Graph esteja ativado.
você precisa ir para SEO ” Social e selecionar a opção “Enabled” (Ativado) em “Add Open Graph meta data” (Adicionar metadados do Open Graph).
Você pode salvar suas configurações ou continuar e configurar outras opções sociais do Facebook.
Você pode fornecer um ID de aplicativo do Facebook se usar um para sua página do Facebook e insights. Você também pode alterar o título, a descrição e a imagem da meta-página inicial do Open Graph.
Por fim, você pode definir uma imagem padrão a ser usada quando nenhuma imagem for definida para um post ou uma página.
A versão Premium do Yoast SEO também permite que você defina metadados do Open Graph para posts e páginas individuais. Basta editar um post ou página e rolar para baixo até a seção “Yoast SEO” abaixo do editor.
A partir daí, você pode definir uma miniatura do Facebook para essa postagem ou página específica. Se você não definir um título ou uma descrição do post, o plug-in usará seu metatítulo e sua descrição de SEO.
Agora você pode salvar seu post ou página, e o plug-in armazenará os metadados do Facebook Open Graph.
Método 3: Adicionar metadados do Facebook Open Graph usando código
Esse método normalmente exige que você copie e cole o código no arquivo functions.php do seu tema. No entanto, recomendamos adicionar o código usando o plug-in WPCode, que torna mais fácil e seguro adicionar código personalizado no WordPress.
O WPCode também vem com uma biblioteca de snippets de código prontos, incluindo um para adicionar tags básicas do Open Graph, portanto, são necessários apenas alguns cliques.
Primeiro, instale e ative o plug-in gratuito WPCode. Para obter mais detalhes, consulte nosso guia sobre como instalar um plug-in do WordPress.
Após a ativação, você pode ir para Code Snippets ” + Add Snippet no painel do WordPress.
Procure o snippet “Adicionar tags básicas do Open Graph” na biblioteca. Depois de encontrá-lo, passe o mouse sobre ele e clique no botão “Usar snippet”.
Em seguida, o WPCode adicionará automaticamente o código para você, além de definir o cabeçalho de todo o site como o local do método de inserção.
Depois disso, tudo o que você precisa fazer é alternar o snippet para “Active” (Ativo) e clicar no botão “Update” (Atualizar). Seu tema agora começará a exibir os metadados do Facebook Open Graph no cabeçalho do WordPress.
Se você for um usuário avançado, ainda poderá copiar e colar o código abaixo no arquivo functions.php do seu tema.
Como isso exige que você edite diretamente os arquivos do tema, certifique-se de fazer backup dos arquivos do tema antes de fazer qualquer alteração.
//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 );
Lembre-se de adicionar o nome do seu site na Linha 17, onde está escrito “Your Site Name Goes Here”. Depois disso, altere o URL padrão da imagem na linha 19 com um de seus próprios URLs de imagem.
Recomendamos que você coloque uma imagem com seu logotipo ali, de modo que, se a postagem não tiver uma miniatura, ela puxará o logotipo do seu site.
Você também precisa adicionar seu próprio Facebook App ID na Linha 13. Se você não tiver um aplicativo do Facebook, poderá remover a Linha 13 do código.
Guias especializados sobre Facebook e WordPress
Agora que você sabe como adicionar metadados do Facebook Open Graph, talvez queira ver outros guias relacionados a como usar o Facebook no WordPress:
- Melhores dicas e tutoriais do Facebook para usuários do WordPress
- Como publicar automaticamente no Facebook a partir do WordPress
- Como instalar e configurar comentários do Facebook no WordPress
- Como criar um feed personalizado do Facebook no WordPress
- Como exibir as avaliações de sua página do Facebook no WordPress
- Como corrigir o problema da miniatura incorreta do Facebook no WordPress
- Como exibir o Twitter e o Facebook do autor na página de perfil
- Como criar uma página de destino de anúncios do Facebook no WordPress
- Como corrigir o problema de oEmbed do Facebook e do Instagram no WordPress
Esperamos que este artigo tenha ajudado você a adicionar metadados do Facebook Open Graph no WordPress. Talvez você também queira ver nosso guia sobre como realizar um sorteio ou concurso no WordPress ou nossas escolhas de especialistas sobre os melhores plug-ins do Facebook para expandir seu blog.
Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.
WPBeginner Staff
Did you set a featured image? did you replace the default image URL in the code with your own image URL?
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!
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?
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.
adepush
Hi, is your plugin still available on WordPress.org?
http://wordpress.org/plugins/facebook-open-graph-meta-in-wordpress/
a.
M
its still pulling the image from the sidebar instead of the image i have put in the functions file?
damian
What about og:description?
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
Hassan
its not working for me when i share my posts on face book its only shows my last instagram pics
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?
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!
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?
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
Jim
Works well – thanks. This is still the best way to integrate without a plugin, yes?
Editorial Staff
We are using WordPress SEO by Yoast plugin to do this.
Administrador
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
Editorial Staff
Just use Yoast’s SEO plugin and it has this built-in.
Administrador
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.
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
Editorial Staff
You most certainly can with conditional statements.
Administrador
Editorial Staff
You have to attach the post thumbnail using the featured image function.
Administrador
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.
seitanist
This worked great! Thanks!!!
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
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?
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!
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.
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?
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.
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.
MetalPhil
BTW: I installed it a long time ago and it still doesn’t work. I’ve been having this problem for over a month now. It’s killing me.
lizbizz
I Deactivated the Facebook OG Meta plugin on my blog and Installed the Simple Facebook Connect plugin instead and now everything seems to be working right on my site and posts!
WPbeginners. com instructions and info (be sure to follow them exactly) using this post: https://www.wpbeginner.com/plugins/how-to-install-and-setup-simple-facebook-connect-for-wordpress/
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?
SaijoGeorge
@wpbeginner Facepalm … Thanks for the quick replay mate
wpbeginner
@SaijoGeorge It will only output your post’s defined excerpt. If you don’t specify an excerpt, then nothing will be displayed.
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
wpbeginner
@CarlosDeGuzman It takes a while for the linter to update.
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
wpbeginner
@ReyCalantaol It has nothing to do with SEO…. the Open Graph data is for Facebook…..
wpbeginner
@arabsciences@Tia Peterson You have to add the Meta Description and our plugin does that for you…
wpbeginner
@arabsciences@Tia Peterson You have to add the Meta Description and our plugin does that for you…
wpbeginner
@Tia Peterson Yes, you would need to re-install through the repository.
wpbeginner
@Tia Peterson Yes, you would need to re-install through the repository.
Tia Peterson
@arabsciences@wpbeginner Nope.
arabsciences
Hi
How do pull description from aal in one seo plugin.?
it it not working for me
arabsciences
@Tia Peterson@wpbeginner
I use All in one seo plugin and could not pull the description to show in url linter
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)); ?>” />
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?
wpbeginner
@ClyoBeck Make sure that there are no extra spaces at the bottom of the functions.php file …
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?
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?
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).
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…
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.
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!
wpbeginner
@SteveJoseph Facebook takes a bit long to update older posts, but it will fix itself.