Skip to content

Instantly share code, notes, and snippets.

@juyal-ahmed
Last active August 29, 2015 14:07
Show Gist options
  • Save juyal-ahmed/ab5e46f4164e9ff69043 to your computer and use it in GitHub Desktop.
Save juyal-ahmed/ab5e46f4164e9ff69043 to your computer and use it in GitHub Desktop.
Adding Open Graph Content on WordPress
<?php
if ( !function_exists( 'mondira_add_opengraph' ) ) {
function mondira_add_opengraph() {
global $post;
if ( empty( $post ) ) {
return "";
}
echo "\n<!-- " . get_bloginfo( 'name' ) . " Open Graph Tags -->\n";
echo "<meta property='og:site_name' content='". get_bloginfo( 'name' ) ."'/>\n";
echo "<meta property='og:url' content='" . get_permalink() . "'/>\n";
if ( is_singular() ) {
echo "<meta property='og:title' content='" . get_the_title() . "'/>\n";
echo "<meta property='og:type' content='article'/>\n";
$content = ( !empty( $post->post_excerpt ) ) ?
wp_trim_words( strip_shortcodes( $post->post_excerpt ), 30 ) :
wp_trim_words( strip_shortcodes( $post->post_content ), 30 );
if ( empty( $content ) ) {
$content = "Visit the post for more.";
}
echo "<meta property='og:description' content='" . $content . "' />\n";
} elseif( is_front_page() or is_home() ) {
echo "<meta property='og:title' content='" . get_bloginfo( "name" ) . "'/>\n";
echo "<meta property='og:type' content='website'/>\n";
}
if( has_post_thumbnail( $post->ID ) ) {
$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'large' );
echo "<meta property='og:image' content='" . esc_attr( $thumbnail[0] ) . "'/>\n";
}
echo "\n";
}
}
if ( !defined('WPSEO_VERSION') && !class_exists('NY_OG_Admin')) {
add_action( 'wp_head', 'mondira_add_opengraph', 5 );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment