Home > Dev > WordPress SEO > Add Open Graph Tags for Social Sharing

Add Open Graph Tags for Social Sharing

This code adds Open Graph meta tags for better social media sharing.

// Add this to your theme's functions.php file

function add_open_graph_tags() {
    global $post;
    if (is_single() || is_page()) {
        echo '<meta property="og:title" content="' . get_the_title() . '">';
        echo '<meta property="og:description" content="' . get_the_excerpt() . '">';
        echo '<meta property="og:url" content="' . get_permalink() . '">';
        echo '<meta property="og:type" content="article">';
        if (has_post_thumbnail($post->ID)) {
            $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
            echo '<meta property="og:image" content="' . esc_url($thumbnail[0]) . '">';
        }
    }
}
add_action('wp_head', 'add_open_graph_tags');
Back