Add open graph meta without a plugin

Open Graph tags need to be printed in the website header and contain content and technical information about our site, like country, language, title, and image to display on social networks (even different from what we show on site).

So we can use the wp_head hook to add them to WordPress using any theme. Let’s wrap the code up:

add_action(‘wp_head’, ‘fc_opengraph’);
function fc_opengraph() {
if( is_single() || is_page() ) {
$post_id = get_queried_object_id();
$url = get_permalink($post_id);
$title = get_the_title($post_id);
$site_name = get_bloginfo(‘name’);
$description = wp_trim_words( get_post_field(‘post_content’, $post_id), 25 );
$image = get_the_post_thumbnail_url($post_id);
if( !empty( get_post_meta($post_id, ‘og_image’, true) ) ) $image = get_post_meta($post_id, ‘og_image’, true);
$locale = get_locale();
echo ‘<meta property=og:locale content=‘ . esc_attr($locale) . ‘ />’;
echo ‘<meta property=og:type content=article />’;
echo ‘<meta property=og:title content=‘ . esc_attr($title) . ‘ | ‘ . esc_attr($site_name) . ‘ />’;
echo ‘<meta property=og:description content=‘ . esc_attr($description) . ‘ />’;
echo ‘<meta property=og:url content=‘ . esc_url($url) . ‘ />’;
echo ‘<meta property=og:site_name content=‘ . esc_attr($site_name) . ‘ />’;
if($image) echo ‘<meta property=og:image content=‘ . esc_url($image) . ‘ />’;
// Twitter Card
echo ‘<meta name=twitter:card content=summary_large_image />’;
echo ‘<meta name=twitter:site content=@francecarlucci />’;
echo ‘<meta name=twitter:creator content=@francecarlucci />’;
view raw fc_opengraph.php hosted with ❤ by GitHub

I run this code on my own site, but is important to highlight some details you may want to understand or change:

  • I am the only author on my blog, that’s why I use a fixed value for twitter:creator tag
  • I need tags only on post and pages, but if you run a more complex site with custom post types like products, events, jobs, you will need to to a better use of og:type tag
  • sometimes I wanna display a different featured image on social media, so I added an og_image custom field but this is not something really needed
  • if you run a multilingual site, you will need to add some more conditionals to add the og:locale tag

Now you have enough material to start testing code on your site and master your open graphs and social sharing look.

Until next time,

svg3 min read
Subscribe & Follow
Trending Now