Volete aggiungere i metadati di Facebook Open Graph ai vostri temi WordPress?
I metadati Open Graph aiutano Facebook e altri siti web di social media a ottenere informazioni sui vostri post e pagine di WordPress. Inoltre, vi permette di controllare il modo in cui i vostri contenuti appaiono quando vengono condivisi su Facebook.
In questo articolo vi mostreremo come aggiungere facilmente i metadati di Facebook Open Graph nei temi WordPress.
Condivideremo tre metodi diversi, in modo che possiate scegliere quello che funziona meglio per il vostro sito WordPress:
Metodo 1: Aggiungere i metadati Open Graph di Facebook con AIOSEO
All in One SEO è un popolare plugin SEO per WordPress utilizzato da oltre 3 milioni di siti web. Consente di ottimizzare facilmente il sito web per i motori di ricerca e per le piattaforme sociali come Facebook e Twitter.
Innanzitutto, è necessario installare e attivare il plugin gratuito All in One SEO. Per maggiori dettagli, consultate la nostra guida passo passo su come installare un plugin di WordPress.
Dopo l’attivazione, è necessario visitare la pagina All in One SEO ” Reti sociali. Qui è possibile inserire l’URL della propria pagina Facebook e di tutti gli altri social network.
Quindi, fate clic sulla scheda Facebook nella parte superiore della pagina e vedrete che Open Graph Markup è abilitato per impostazione predefinita.
È possibile fare clic sul pulsante “Carica o seleziona immagine” per scegliere un’immagine OG di Facebook predefinita se un articolo non ha un’immagine Open Graph.
Scorrendo verso il basso, è possibile personalizzare il nome del sito, la descrizione e altre impostazioni. Non dimenticate di fare clic sul pulsante blu “Salva modifiche” una volta terminato.
Dopo aver impostato i metatag Open Graph per tutto il sito, il passo successivo è aggiungere i metadati Open Graph per i singoli post e pagine.
Per impostazione predefinita, AIOSEO utilizzerà il titolo e la descrizione del post per il titolo e la descrizione di Open Graph. È inoltre possibile impostare manualmente la miniatura di Facebook per ogni pagina e post.
È sufficiente modificare il post o la pagina e scorrere fino alla sezione “Impostazioni AIOSEO” sotto l’editor. Da qui, passate alla scheda Social e vedrete un’anteprima della vostra miniatura.
Qui è possibile impostare l’immagine del social media, il titolo e la descrizione.
Basta scorrere verso il basso fino al campo “Fonte dell’immagine”. Si può scegliere di utilizzare l’immagine in evidenza, caricare un’immagine personalizzata o altre opzioni.
Metodo 2: Impostare i metadati Open Graph di Facebook con Yoast SEO
Yoast SEO è un altro plugin SEO per WordPress che può essere utilizzato per aggiungere i metadati di Facebook Open Graph a qualsiasi sito WordPress.
La prima cosa da fare è installare e attivare il plugin Yoast SEO. Per maggiori dettagli, consultate la nostra guida passo passo su come installare un plugin di WordPress.
Una volta attivati, i dati Open Graph di Facebook sono abilitati di default.
È possibile verificarlo andando su Yoast SEO ” Impostazioni e scorrendo giù fino alla sezione Condivisione sociale. Ora è possibile verificare che la caratteristica dei dati Open Graph sia abilitata.
è necessario andare in SEO ” Social e selezionare l’opzione ‘Abilitato’ in ‘Aggiungi meta dati Open Graph’.
È possibile salvare le impostazioni o continuare a configurare altre opzioni sociali di Facebook.
È possibile fornire l’ID dell’app di Facebook se si utilizza una pagina Facebook e gli insight. Potete anche modificare il titolo, la descrizione e l’immagine della vostra homepage Open Graph.
Infine, è possibile impostare un’immagine predefinita da utilizzare quando non è stata impostata alcuna immagine per un post o una pagina.
La versione Premium di Yoast SEO consente anche di impostare i metadati Open Graph per le singole pagine e post. È sufficiente editare una pagina o un post e scorrere verso il basso fino alla sezione “Yoast SEO” sotto l’editor.
Da qui è possibile impostare una miniatura Facebook per quel particolare post o pagina. Se non si imposta un titolo o una descrizione del post, il plugin utilizzerà il meta titolo e la descrizione SEO.
Ora è possibile salvare il post o la pagina e il plugin memorizzerà i metadati di Facebook Open Graph.
Metodo 3: Aggiungere i metadati Open Graph di Facebook con il codice
Questo metodo richiede la modifica dei file del tema, quindi assicuratevi di eseguire un backup dei file del tema prima di apportare qualsiasi modifica.
Dopodiché, è sufficiente copiare e incollare questo codice nel file functions.php del tema o aggiungere il frammento di codice utilizzando il plugin WPCode (consigliato).
Innanzitutto, installare e attivare il plugin gratuito WPCode. Per maggiori dettagli, consultare la nostra guida su come installare un plugin di WordPress.
Dopo l’attivazione, è possibile andare su Code Snippets ” + Add Snippet dalla dashboard di WordPress. Dovete passare sopra il primo snippet con l’etichetta “Aggiungi il tuo codice personalizzato (nuovo snippet)” e fare clic sul pulsante “Usa snippet”.
Verrà creato un nuovo snippet in cui si dovrà digitare un titolo e selezionare il tipo di codice “Snippet PHP”. Dopodiché, è necessario inserire il seguente codice nella sezione “Anteprima del codice”:
//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 );
Ricordarsi di aggiungere il nome del sito alla riga 17, dove è scritto “Il nome del sito va qui”. Successivamente, è necessario modificare l’URL dell’immagine predefinito alla riga 19 con uno dei propri URL dell’immagine.
Si consiglia di inserire un’immagine con il proprio logo, in modo che, se il post non ha una miniatura, venga estratto il logo del sito.
È inoltre necessario aggiungere l’ID dell’applicazione di Facebook alla riga 13. Se non si dispone di un’applicazione Facebook, è possibile rimuovere la riga 13 dal codice.
Una volta terminato l’aggiornamento del codice, è necessario impostare lo snippet su “attivo” e fare clic sul pulsante “Salva snippet”. Il vostro tema inizierà a mostrare i metadati di Facebook Open Graph nell’intestazione di WordPress.
Guide di esperti su Facebook e WordPress
Ora che sapete come aggiungere i metadati di Facebook Open Graph, potreste voler vedere altre guide su come utilizzare Facebook in WordPress:
- I migliori suggerimenti e tutorial su Facebook per gli utenti di WordPress
- Come postare automaticamente su Facebook da WordPress
- Come installare e configurare i commenti di Facebook in WordPress
- Come creare un feed Facebook personalizzato in WordPress
- Come visualizzare le recensioni della pagina Facebook in WordPress
- Come risolvere il problema delle miniature errate di Facebook in WordPress
- Come visualizzare Twitter e Facebook dell’autore nella pagina del profilo
- Come creare una pagina di destinazione di Facebook Ads in WordPress
- Come risolvere il problema di Facebook e Instagram oEmbed in WordPress
Speriamo che questo articolo vi abbia aiutato ad aggiungere i metadati di Facebook Open Graph in WordPress. Potreste anche voler consultare la nostra guida su come gestire un’offerta o un concorso in WordPress o la nostra scelta dei migliori plugin per Facebook per far crescere il vostro blog.
Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.
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!
Daniel says
This is indeed helpful but SEO Yoast’s interface doesn’t look like this anymore. This needs updating.
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
Admin
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.
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!
WPBeginner Support says
The code snippet should set your featured image to the featured image of the post.
Admin
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.
Admin
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
Admin
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.
Admin
Richard S. says
Wow, this really worked for me, you’re awesome!
WPBeginner Support says
Glad our guide was helpful
Admin
evelien says
You did it again – looking for a solution, and you deliver ! You rule
WPBeginner Support says
Glad our guide was helpful
Admin
Eddie says
Does this also work for sms text message url previews or just Facebook?
WPBeginner Support says
While not specifically for SMS messages, the markup helps with that as well.
Admin
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
Admin
Indranil Paul says
I’m facing this problem in all social sharing sites.
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.
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.
Admin
Colin says
My title looks like this in the preview:
%%title%% %%page%% %%sep%% %%sitename%%
How do I fix this?
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
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
WPBeginner Support says
Hi Sadie,
You can add it to either functions.php file.
Admin
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.
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?
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..
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.
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!
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..?
elsa says
This plugin gave me a white screen of death, obviously a conflict with something or memory exceeded
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?
Nikki says
Hi Jin, Did you ever get an answer to your question? I’m looking for the same information.
Thank yoU!
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
Martin says
Does my Facebook profile have to be public in order for my Facebook User ID to be good to use here?
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?
WPBeginner Support says
Hi Martin,
Yes it would work.
Admin
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?
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()
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!
Mohsin Rafique says
Nicely explained & works like a charm.
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?
Michelle says
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 says
Same problem here.
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!
WPBeginner Support says
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 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?
giovanna says
Hi can you help me please? I added the code in function and what I have to add in the head please?
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 ”;
}
benjamin says
I just want to say thanks! … this is very helpful, you the best!
WPBeginner Support says
Glad you found it helpful. Don’t forget to follow us on Facebook for more WordPress tips and tutorials.
Admin
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!
WPBeginner Support says
You need to enter your WordPress site URL in the debug tool.
Admin
Courtney says
Hi there,
I have SEO Yoast and I uploaded the new image and its still not working on facebook……???
MassimoDIFA says
Thank you, manually added open graph on header, perfect!! Thank you!!
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.
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?
Mahmud Ayaz says
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 says
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 says
I have the same problem, also getting og:description missing
amelliya says
me too – any help?
AC says
I have the same problem, and I cannot use FB debugger because i work in localhost…
Marc says
this worked for me:
$metadesc = strip_tags(get_post_field(‘post_content’, $post->ID));
echo ”;
(my posts had a very short content)
Kim McCann says
The following works by pulling from your excerpt. Just add under og:title
WPBeginner Staff says
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 says
Thank you for taking the time to reply. Will give it a shot!
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?
Naren Patel says
Thank you very much, I really want this information.
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.
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?
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??????
Anas Khan says
Great tutorial, i want to know is there any tutorial about open graph meta for Google Plus ?