Created
May 3, 2018 16:08
-
-
Save ksascomm/f7481f907bc8c17deba63d4a4892da4b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function add_opengraph_doctype($output) { | |
return $output . ' | |
xmlns="https://www.w3.org/1999/xhtml" | |
xmlns:og="https://ogp.me/ns#" | |
xmlns:fb="http://www.facebook.com/2008/fbml"'; | |
} | |
add_filter('language_attributes', 'add_opengraph_doctype'); | |
//Add Open Graph Meta Info from the actual article data, or customize as necessary | |
function facebook_open_graph() { | |
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'); | |
} | |
//You'll need to find you Facebook profile Id and add it as the admin | |
echo '<meta property="fb:admins" content="XXXXXXXXX-fb-admin-id"/>'; | |
echo '<meta property="og:title" content="' . get_the_title() . '"/>'; | |
echo '<meta property="og:description" content="' . $excerpt . '"/>'; | |
echo '<meta property="og:type" content="article"/>'; | |
echo '<meta property="og:url" content="' . get_permalink() . '"/>'; | |
//Let's also add some Twitter related meta data | |
echo '<meta name="twitter:card" content="summary" />'; | |
//This is the site Twitter @username to be used at the footer of the card | |
echo '<meta name="twitter:site" content="@site_user_name" />'; | |
//This the Twitter @username which is the creator / author of the article | |
echo '<meta name="twitter:creator" content="@username_author" />'; | |
// Customize the below with the name of your site | |
echo '<meta property="og:site_name" content="'. get_bloginfo( 'title' ) .'"/>'; | |
if(!has_post_thumbnail( $post->ID )) { //the post does not have featured image, use a default image | |
//Create a default image on your server or an image in your media library, and insert it's URL here | |
$default_image= get_template_directory_uri() . '/dist/assets/images/homepage-slider-hero.jpg"'; | |
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', 'facebook_open_graph', 5 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment