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

Como adicionar metadados do Facebook Open Graph em temas do WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Deseja adicionar metadados do Facebook Open Graph aos seus temas do WordPress?

Os metadados do Open Graph ajudam o Facebook e outros sites de mídia social a obter informações sobre suas publicações e páginas do WordPress. Eles também permitem que você controle como seu conteúdo é exibido quando compartilhado no Facebook.

Neste artigo, mostraremos a você como adicionar facilmente metadados do Facebook Open Graph em temas do WordPress.

Add Facebook open graph meta data in any WordPress theme

Compartilharemos três métodos diferentes para que você possa escolher o que funciona melhor para o seu site WordPress:

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.

AIOSEO social network settings

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.

Set default Open Graph image

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.

AIOSEO Facebook preview

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.

Choose which WordPress image to use as your Facebook thumbnail

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.

Depois de 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).

Enable Facebook 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.

O Yoast SEO também permite que você defina metadados do Open Graph para posts e páginas individuais. Basta editar um post ou uma página e rolar para baixo até a seção “Yoast SEO”, abaixo do editor.

Set open graph meta data for post and pages

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 requer a edição dos arquivos do tema, portanto, certifique-se de fazer backup dos arquivos do tema antes de fazer qualquer alteração.

Depois disso, basta copiar e colar esse código no arquivo functions.php do seu tema ou adicionar o trecho de código usando o plug-in WPCode (recomendado).

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. Você precisa passar o mouse sobre o primeiro snippet denominado “Add Your Custom Code (New Snippet)” e clicar no botão “Use snippet”.

Adding Your Custom Code in WPCode

Isso criará um novo snippet no qual você precisará digitar um título e selecionar o tipo de código “PHP Snippet”. Depois disso, você precisa postar o seguinte código na seção “Code Preview” (Visualização de código):

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

The New Code Snippet in WPCode

Quando terminar de atualizar o código, você precisará alternar o snippet para “Ativo” e clicar no botão “Salvar snippet”. Seu tema agora começará a exibir os metadados do Facebook Open Graph no cabeçalho do WordPress.

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:

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.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo 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.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

222 ComentáriosDeixe uma resposta

  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!

    • WPBeginner Support says

      Thank you for letting us know that their interface has been updated, we will look to update it when we update the article :)

      Administrador

  2. Jiří Vaněk says

    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.

  3. Harry Goldhagen says

    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!

  4. Kiss Attila says

    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 says

      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

  5. rehman says

    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 says

      You should not need to modify the code to work with custom post types and it should work on them :)

      Administrador

  6. gabriele biagini says

    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 says

      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

  7. Indranil Paul says

    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 says

      That would depend on your site’s caching and any caching on Facebook for how long it takes

      Administrador

        • WPBeginner Support says

          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.

  8. Udaya Bhaskar says

    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 says

      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

  9. Pramod Singh says

    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

  10. Sadie says

    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

  11. Max says

    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.

  12. Laura says

    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?

  13. Suraj says

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

  14. Malik Adil says

    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.

  15. Eric Hepperle says

    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!

  16. Mahesh Yadav says

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

  17. Jin Miller says

    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?

  18. Vic says

    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

  19. Martin says

    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?

  20. Jordan Carter says

    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?

  21. Wagner Lungov says

    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 says

      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()

  22. Jolanda says

    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!

  23. Devyn says

    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?

    • Glenford says

      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 says

        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!

  24. joe Barrett says

    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?

  25. benjamin s says

    Here’s also a nice improvement to make an exception for the home-page:

    if (is_front_page()){
    echo ”;
    echo ”;
    echo ”;
    }else{
    echo ”;
    echo ”;
    }

  26. Laura K says

    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!

  27. D says

    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.

  28. Amanda Paul says

    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?

  29. BK says

    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?

  30. Robin says

    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.

  31. Maria says

    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?

  32. Salih Kulangara says

    @ 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??????

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.