Add Open Graph and Twitter card tags to posts and pages so links share with the right title, description and image, and step aside when an SEO plugin is active.
add_action( 'wp_head', function (): void {
// SEO plugins already print these tags, so step aside if one is active.
if ( ! is_singular() || defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'SLIM_SEO_VER' ) || defined( 'SEOPRESS_VERSION' ) || defined( 'AIOSEO_VERSION' ) ) {
return;
}
$post = get_queried_object();
$description = has_excerpt( $post ) ? get_the_excerpt( $post ) : wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ), 30, '…' );
$image = get_the_post_thumbnail_url( $post, 'large' );
$tags = [
'og:type' => 'post' === $post->post_type ? 'article' : 'website',
'og:title' => wp_strip_all_tags( get_the_title( $post ) ),
'og:description' => $description,
'og:url' => get_permalink( $post ),
'og:site_name' => get_bloginfo( 'name' ),
'og:image' => $image ?: '',
'twitter:card' => $image ? 'summary_large_image' : 'summary',
];
foreach ( array_filter( $tags ) as $property => $content ) {
$attr = str_starts_with( $property, 'twitter:' ) ? 'name' : 'property';
printf( '<meta %s="%s" content="%s">' . "\n", $attr, esc_attr( $property ), esc_attr( $content ) );
}
}, 5 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
When someone shares a link on Facebook, LinkedIn, Slack or X, those sites read Open Graph tags from the page head to build the preview card. Without them they guess, often picking the wrong image or a random sentence. This snippet adds the essential tags to every post, page and public custom post type.
The snippet runs early in wp_head on single views only. It uses the post excerpt as the description when there is one, and otherwise the first 30 words of the content with shortcodes and HTML removed. The featured image becomes og:image, and the Twitter card switches to the large-image layout when an image exists.
Blog posts get og:type set to article. Pages and other types get website, which is what the Open Graph spec expects. Every value goes through esc_attr(), and empty values are skipped instead of printed as blank tags.
large size is usually 1024 pixels wide, so change it to full if your previews look small.Open a post, view the page source and search for og:title. You should see one set of tags. Then paste the URL into the Sharing Debugger and check the preview.