Updated: 01/12/2023

Published: 30/11/2023

By Peter K

SEO Snippet

This is a snippet to use for websites that do not have a facebook opengraph meta tag.

To use this snippet

 

  • Add it into the functions.php file in your theme, (prefereably child theme)
  • Update the default image with the required url
  • Test.
<?php



// Code by Microbite Websites
// Inspired by https://www.wpbeginner.com/wp-themes/how-to-add-facebook-open-graph-meta-data-in-wordpress-themes/
// and https://www.elegantthemes.com/blog/tips-tricks/how-to-add-open-graph-tags-to-wordpress

//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() {
  
  $default_image="http://www.example.com/wp-content/uploads/Main-page-top-791x400-1.png";
  

  
  global $post;
  
  
    if ( !is_singular()) //if it is not a post or a page
        return;

        if($excerpt = $post->post_excerpt) {
            $excerpt = strip_tags($post->post_excerpt);
            $excerpt = str_replace("", "'", $excerpt);
        } else {
            $excerpt = get_bloginfo('description');
        }	
	
        echo '<meta property="og:title" content="' . get_the_title() . '"/>';
        echo '<meta property="og:type" content="article"/>';
		echo '<meta property="og:description" content="' . $excerpt . '"/>';
        echo '<meta property="og:url" content="' . get_permalink() . '"/>';
        echo '<meta property="og:site_name" content="' . get_bloginfo() .'"/>';
       echo '<meta property="og:site_name" content="' . get_bloginfo() .'"/>';
    if(!has_post_thumbnail( $post->ID )) { //the post does not have featured image, use a default image
         //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 );


?>