I wanted a way to set-up WordPress in such a way so that when your website homepage or an article is shared, the relevant title, description and image shows up on Facebook.
When you normal share a website page, Facebook will automatically scrape the content for the relevant information.
This is a precise way to tell Facebook exactly which meta content you want to use.
WordPress Facebook sharing code
Enter this code in the <head> section of your header.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php if (have_posts()):while(have_posts()):the_post(); endwhile; endif;?> <!-- if page is home page --> <?php if (have_posts()):while(have_posts()):the_post(); endwhile; endif;?> <!-- if page is home page --> <?php if (is_home() || is_front_page() ) { ?> <meta property="og:url" content="<?php bloginfo('url') ?>"/> <meta property="og:title" content="<?php bloginfo('name'); ?>" /> <meta property="og:description" content="<?php bloginfo('description'); ?>" /> <meta property="og:type" content="website" /> <meta property="og:image" content="<?php bloginfo('template_directory');?>/img/logo.jpg" /> <meta property="og:site_name" content="<?php bloginfo('name'); ?>"/> <!-- if page is single post --> <?php } elseif (is_single()) { ?> <meta property="og:url" content="<?php the_permalink() ?>"/> <meta property="og:title" content="<?php single_post_title(''); ?>" /> <meta property="og:description" content="<?php echo strip_tags(get_the_excerpt($post->ID)); ?>" /> <meta property="og:type" content="article" /> <meta property="og:image" content="<?php if ( has_post_thumbnail() ) { $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), '', false, '' ); echo $src[0]; } else { ?><?php bloginfo('template_directory');?>/img/logo.jpg<?php } ?>"/> <meta property="og:site_name" content="<?php bloginfo('name'); ?>"/> <!-- if page is others --> <?php } else { ?> <meta property="og:description" content="<?php bloginfo('description'); ?>" /> <meta property="og:type" content="website" /> <meta property="og:image" content="<?php bloginfo('template_directory');?>/img/logo.jpg" /> <?php } ?> <meta property="og:site_name" content="<?php bloginfo('name'); ?>" /> |
Explanation
The code is divided up into 3 blocks which will function whether the current page is the home page, a single post page or other page.
The part that tells Facebook which image to use (line 15, 26 and 34) has been set up to display a backup image if there is no featured image to use. In this case it’s set to logo.jpg in the /img/ folder in your template directory so make sure to set that.
