This function runs conditional checks delivering relevant information to social media platforms using the Open Graph Protocol to deliver meta data to search engines and social media platforms about the WordPress post.
<?php
function jd_opengraph_meta_tags() {
if ( has_custom_logo() ) {
$custom_logo_id = get_theme_mod( 'custom_logo' );
$image = wp_get_attachment_image_src( $custom_logo_id , 'full' );
$image = $image[0];
}
if (is_home() || is_front_page() ) {
$description = wp_strip_all_tags( get_bloginfo('description') );
$permalink = get_home_url();
$title = wp_strip_all_tags( get_bloginfo('name') );
} elseif ( is_archive() ) {
$description = wp_strip_all_tags( term_description() );
$permalink = get_post_type_archive_link( 'post' );
$title = wp_strip_all_tags( get_the_archive_title() );
} else {
if (has_post_thumbnail() ) {
$image = get_the_post_thumbnail_url();
} else {
$custom_logo_id = get_theme_mod( 'custom_logo' );
$image = wp_get_attachment_image_src( $custom_logo_id , 'full' );
$image = $image[0];
}
$permalink = get_permalink();
$title = get_the_title();
$description = get_the_excerpt();
}
// Open Graph
echo '<meta property="og:title" content="' . $title . '" />';
echo '<meta name="description" content="'. $description . '">';
echo '<meta property="og:type" content="website" />';
echo '<meta property="og:url" content="' . $permalink . '" />';
echo '<meta property="og:image" content="' . $image . '" />';
// Twitter Card
echo '<meta name="twitter:card" content="summary_large_image">';
echo '<meta property="twitter:domain" content="' . get_home_url() . '">';
echo '<meta property="twitter:url" content="' . $permalink . '">';
echo '<meta name="twitter:title" content="' . $title . '">';
echo '<meta name="twitter:description" content="' . $description .'">';
echo '<meta name="twitter:image" content="' . $image . '">';
}
add_action('wp_head', 'jd_opengraph_meta_tags');