How to Add Open Graph Information Dynamically

How to Add Open Graph Information Dynamically

The purpose of this post is to give very simple instructions that will help you add Open Graph information to your posts and pages.

Straight to the Code

How to Add Open Graph Information Dynamically

What is Open Graph Information?
It is a set of meta information that lets you tell social media platforms what to show when someone links to your website. It can be very useful for adding an extra level of professionalism to your web presence. It is a nice way to enhance your free social media marketing through your connections, and improve your click through rate.

Do I Need To Be A Nerd To Set This Up?
No, but it helps 😉 If you are scared by code or don’t know what FTP means click here or here and follow the steps to install and set up one of these plugin.

If you don’t mind copy and pasting code into a php file keep scrolling.

The first step is to add a function that lets social media platforms know you are using the Open Graph protocol. It alerts these platforms to the presence of our Open Graph functions and it helps them be able to read the meta we will add in a second. There is no need to change any of the code. It can be pasted into your functions.php file. The path to the functions.php file is root -> wp-content -> themes -> “active theme name” -> functions.php.

function doctype_opengraph($output) {
    return $output . '
    xmlns:og="http://opengraphprotocol.org/schema/"
    xmlns:fb="http://www.facebook.com/2008/fbml"';
}
add_filter('language_attributes', 'doctype_opengraph');

The next step is to dynamically add Open Graph information to each post and page on your site. That is done by pasting the following code into your functions.php file below the code you just added. The only thing that needs to be changed is the default Open Graph Image. This image will show if there is no featured image on the page or post. Just paste the url of the image you want where I have written URL-OF-DEFAULT-IMAGE-GOES-HERE.

function opengraph_function() {
    global $post;

    if(is_single()) {
        if(has_post_thumbnail($post->ID)) {
            $img_src = wp_get_attachment_image_src(get_post_thumbnail_id( $post->ID ), 'medium'); // Get page or post featured image
        } else {
            $img_src = 'URL-OF-DEFAULT-IMAGE-GOES-HERE'; // Set Default image if featured image doesn't exist.
        }
        if($excerpt = $post->post_excerpt) {
            $excerpt = strip_tags($post->post_excerpt); // Get excerpt
            $excerpt = str_replace("", "'", $excerpt); // Format excerpt
        } else {
            $excerpt = get_bloginfo('description'); // Get site description if no excerpt exists
        }
        ?>   
        <meta property="og:title" content="<?php echo the_title(); ?>"/> // The title that will show up in social media
        <meta property="og:description" content="<?php echo $excerpt; ?>"/> // The excerpt that will show up in social media
        <meta property="og:type" content="article"/> // The content that will show up in social media
        <meta property="og:url" content="<?php echo the_permalink(); ?>"/> // The link that will show up in social media
        <meta property="og:site_name" content="<?php echo get_bloginfo(); ?>"/> // The website title that will show up in social media
        <meta property="og:image" content="<?php echo $img_src; ?>"/> // The image that will show up in social media

      <?php
          } else {  
              return;       //if it is not a page or a post don't print any data
            }  
      }  
      add_action('wp_head', 'opengraph_function', 5); // adds code to the head of every page and post

To test and make sure it worked paste your url in here and click the "scrape" button that will give you a live preview for what will happen.

Thats it, you did it! Pat yourself on the back, you are on your way to becoming a nerd.

If you are using custom fields to add meta descriptions as explained in my post on how to add meta titles and meta descriptions without a plugin, you may want to use this code:

function add_open_graph_tags() {
  if (is_single() || is_page()) {
    global $post;
    setup_postdata($post);
    function get_description() {
      global $post;
      // Check if the 'meta-description' custom field exists
      $meta_description = get_post_meta($post->ID, 'meta_description', true);
      if ($meta_description) {
        return $meta_description;
      }
      // If the 'meta-description' custom field does not exist, get the excerpt from the content
      $excerpt = get_the_content();
      $excerpt = preg_replace(" (\[.*?\])",'',$excerpt);
      $excerpt = strip_shortcodes($excerpt);
      $excerpt = strip_tags($excerpt);
      $excerpt = substr($excerpt, 0, 200);
      $excerpt = substr($excerpt, 0, strripos($excerpt, " "));
      $excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt));
      return $excerpt;
    }
    // Open Graph tags
    echo '<meta property="og:title" content="' . get_the_title() . '"/>' . "\n";
    echo '<meta property="og:type" content="article"/>' . "\n";
    echo '<meta property="og:url" content="' . get_the_permalink() . '"/>' . "\n";
    echo '<meta property="og:description" content="' . get_description() . '"/>' . "\n";
    if (has_post_thumbnail()) {
      $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]) . '"/>' . "\n";
    }
    // Twitter Card tags
    echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
    echo '<meta name="twitter:title" content="' . get_the_title() . '">' . "\n";
    echo '<meta name="twitter:description" content="' . get_description() . '">' . "\n";
    if (has_post_thumbnail()) {
      $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');
      echo '<meta name="twitter:image" content="' . esc_attr($thumbnail_src[0]) . '">' . "\n";
    }
  }
}
add_action('wp_head', 'add_open_graph_tags');

We will be happy to hear your thoughts

Leave a reply

This website uses cookies and asks your personal data to enhance your browsing experience. We are committed to protecting your privacy and ensuring your data is handled in compliance with the General Data Protection Regulation (GDPR).
RiseDesignID
Logo
Compare items
  • Total (0)
Compare
0
Shopping cart