Social sharing tags (Open Graph)
Adds Open Graph and X card tags, so links to your posts show a title, summary and featured image on Facebook, LinkedIn, X and messaging apps. Skipped when an SEO plugin is active.
<?php
add_action(
'wp_head',
static function () {
if ( defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'AIOSEO_VERSION' ) || defined( 'SEOPRESS_VERSION' ) || class_exists( 'The_SEO_Framework\\Load' ) ) {
return;
}
$tags = array(
'og:site_name' => get_bloginfo( 'name' ),
'og:locale' => get_locale(),
);
if ( is_singular() ) {
$post = get_queried_object();
$description = has_excerpt( $post ) ? $post->post_excerpt : wp_trim_words( strip_shortcodes( $post->post_content ), 30, '…' );
$tags += array(
'og:type' => 'post' === $post->post_type ? 'article' : 'website',
'og:title' => wp_strip_all_tags( get_the_title( $post ) ),
'og:description' => trim( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $description ) ) ),
'og:url' => get_permalink( $post ),
);
$image = get_the_post_thumbnail_url( $post, 'large' );
} else {
$tags += array(
'og:type' => 'website',
'og:title' => wp_get_document_title(),
'og:description' => get_bloginfo( 'description' ),
'og:url' => is_front_page() ? home_url( '/' ) : '',
);
$image = get_site_icon_url( 512 );
}
if ( ! empty( $image ) ) {
$tags['og:image'] = $image;
}
foreach ( array_filter( $tags ) as $property => $content ) {
echo '<meta property="' . esc_attr( $property ) . '" content="' . esc_attr( $content ) . '">' . "\n";
}
echo '<meta name="twitter:card" content="' . ( empty( $image ) ? 'summary' : 'summary_large_image' ) . '">' . "\n";
},
5
);
In these packs
- SEO basics: Meta descriptions, social sharing tags, article structured data and cleaner indexing, for sites without an SEO plugin.