Open Graph and Twitter Cards Meta Tags in WordPress Without a Plugin

Open Graph and Twitter Card tags in WordPress without a plugin

When a link is pasted into Facebook, LinkedIn, Slack or a messenger, the service fetches the page and looks for Open Graph tags: og:title, og:description, og:image. Without them, the preview is a bare URL or a random image from the page. SEO plugins print these tags; a theme without such a plugin needs about 50 lines of PHP.

Problem: The posts of a recipe blog are shared as bare links without an image or a description. The site uses no SEO plugin, and the theme prints only the <title>.

Solution: Print og:* and twitter:* meta tags in wp_head, using the post title, the excerpt (or the beginning of the content) as description, the featured image in a dedicated 1200×630 size with its real dimensions, and a default image from the theme when a post has none.

The image size

add_action( 'after_setup_theme', function (): void {
    add_image_size( 'ha-social', 1200, 630, true );
} );

1200×630 pixels (ratio 1.91:1) is the size Facebook, LinkedIn and X use for large previews. The size is created for new uploads; for existing images, regenerate the thumbnails once (wp media regenerate --image_size=ha-social).

The tags

add_action( 'wp_head', 'ha_social_meta', 5 );
function ha_social_meta(): void {
    if ( is_singular() ) {
        $post        = get_queried_object();
        $type        = 'article';
        $title       = wp_strip_all_tags( get_the_title( $post ) );
        $url         = get_permalink( $post );
        $description = has_excerpt( $post )
            ? get_the_excerpt( $post )
            : wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ), 30, '…' );
        $image       = has_post_thumbnail( $post ) ? wp_get_attachment_image_src( get_post_thumbnail_id( $post ), 'ha-social' ) : false;
    } else {
        $type        = 'website';
        $title       = wp_get_document_title();
        $url         = is_front_page() ? home_url( '/' ) : '';
        $description = get_bloginfo( 'description' );
        $image       = false;
    }

    if ( ! $image ) {
        $image = array( get_theme_file_uri( 'images/social-default.jpg' ), 1200, 630 );
    }

    $tags = array(
        'og:type'             => $type,
        'og:site_name'        => get_bloginfo( 'name' ),
        'og:title'            => $title,
        'og:description'      => $description,
        'og:url'              => $url,
        'og:image'            => $image[0],
        'og:image:width'      => $image[1],
        'og:image:height'     => $image[2],
        'og:locale'           => get_locale(),
        'twitter:card'        => 'summary_large_image',
    );

    foreach ( $tags as $property => $content ) {
        if ( '' === (string) $content ) {
            continue;
        }
        $attr = str_starts_with( $property, 'twitter:' ) ? 'name' : 'property';
        printf( '<meta %s="%s" content="%s">' . "\n", $attr, esc_attr( $property ), esc_attr( $content ) );
    }

    if ( 'article' === $type ) {
        printf( '<meta property="article:published_time" content="%s">' . "\n", esc_attr( get_the_date( 'c', $post ) ) );
        printf( '<meta property="article:modified_time" content="%s">' . "\n", esc_attr( get_the_modified_date( 'c', $post ) ) );
    }
}

Details that matter:

  • og:* tags use the property attribute, twitter:* tags use name. X reads og:title, og:description and og:image as fallback, so only twitter:card is needed in addition.
  • The image URL must be absolute and publicly reachable; wp_get_attachment_image_src() returns an absolute URL. With og:image:width and height, Facebook can show the preview at the first share instead of after a second fetch.
  • get_locale() returns en_US, which is the format Open Graph expects.
  • On archives without a fixed URL, og:url is left out; the services then use the URL that was shared.
  • str_starts_with() needs PHP 8.0; for older PHP use 0 === strpos().

wp_trim_words() on the raw content would include the text of shortcodes, so they are stripped first. Blocks are HTML comments and disappear with wp_strip_all_tags().

Avoid duplicates

If an SEO plugin is installed later, both print tags and the services pick one at random. A check at the top of the function prevents that:

if ( defined( 'WPSEO_VERSION' ) || class_exists( 'RankMath' ) ) {
    return;
}

Test

Facebook caches the preview of a URL for about 30 days. After a change, open the Sharing Debugger (developers.facebook.com/tools/debug), enter the URL and click “Scrape Again”. LinkedIn has the Post Inspector for the same purpose. For a quick look at the tags without a service: curl -s https://example.com/post/ | grep -E 'og:|twitter:'.

NOTE: Pages behind a login, a cookie wall or a bot protection that blocks unknown user agents produce no preview, because the crawlers of the services cannot see the tags. Allow facebookexternalhit, LinkedInBot, Twitterbot and Slackbot in such a protection. Share buttons for the same posts: social media sharing buttons without a plugin.