Overview
Many WordPress themes don’t display preview images or titles when you enter a URL into X (formerly Twitter) by default. While you can install SEO plugins, I’m posting this as a note for those who want to avoid cluttering their site with extra plugins.
Simply add the following code directly to your theme’s functions.php file. This content is intended for the posts page.
add_action( 'wp_head', 'itlibero_output_social_meta', 5 );
function itlibero_output_social_meta() {
if ( is_singular() ) {
global $post;
$title = trim( wp_strip_all_tags( get_the_title( $post ), true ) );
if ( has_excerpt( $post ) ) {
$description = get_the_excerpt( $post );
} else {
$description = wp_trim_words( wp_strip_all_tags( $post->post_content ), 40 );
}
$description = esc_attr( $description );
$url = get_permalink( $post );
if ( has_post_thumbnail( $post ) ) {
$image = get_the_post_thumbnail_url( $post, 'full' );
} else {
$image = home_url( '/wp-content/uploads/default-og-image.jpg' );
}
$site_name = get_bloginfo( 'name' );
?>
<!-- Simple Open Graph / Twitter Card -->
<meta property="og:type" content="article" />
<meta property="og:title" content="<?php echo esc_attr( $title ); ?>" />
<meta property="og:description" content="<?php echo $description; ?>" />
<meta property="og:url" content="<?php echo esc_url( $url ); ?>" />
<meta property="og:site_name" content="<?php echo esc_attr( $site_name ); ?>" />
<meta property="og:image" content="<?php echo esc_url( $image ); ?>" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="<?php echo esc_attr( $title ); ?>" />
<meta name="twitter:description" content="<?php echo $description; ?>" />
<meta name="twitter:image" content="<?php echo esc_url( $image ); ?>" />
<?php
}
}
Ponint
is_singular()is used to display content “only on individual pages like posts or static pages.”- Description:
- If an excerpt exists, use that.
- If not, extract about 40 words from the main text.
- Image:
- If a featured image exists, use that.
- If not, specify /wp-content/uploads/default-og-image.jpg as the default.
- Since `summary_large_image` is specified, X will display a large, landscape-oriented card.
Note
- Disappears when changing themes
→ Write it in the child theme - If there’s a bug in the code, the <head> section might break and cause display issues, so it’s best to quickly check the page source after adding it.







