How to Set Up OG & Twitter Card Tags in WordPress

OG & Twitter Card Tags in WordPress

When a link is shared on social media or messaging platforms, the platform's crawler scrapes the URL to generate a rich snippet. Without specific instructions, these platforms may scrape arbitrary content, often leading to missing images, truncated descriptions, and broken formatting. Open Graph (OG) tags and Twitter Card markup can help solve this issue. They provide editorial control over the headline, preview image, summary text, and routing behavior whenever your content appears in social feeds, Slack, Discord, and messaging apps.

What Are Open Graph and Twitter Card Tags?

The Open Graph Protocol, introduced by Facebook in 2010, has become the industry standard for social platforms. It uses `<meta property="og:*" content="...">` tags placed in the `<head>` section of your HTML document. Platforms like Facebook, LinkedIn, Pinterest, WhatsApp, Telegram, and Discord utilize these tags to create rich link cards. Twitter Cards (for X/Twitter) use `<meta name="twitter:*" content="...">` markup. Although Twitter can fallback on standard Open Graph tags if Twitter-specific tags are absent, defining native Twitter meta tags ensures precise control over layout formats, such as large edge-to-edge banners versus compact square-thumbnail layouts.

Core Tags & Technical Specifications

Let's explain the Open Graph and Twitter Card elements while setting them up in WordPress with Yoast or ACF.

Critical Open Graph Elements:

  • og:title: The headline displayed in the preview (40–60 characters to avoid truncation). Reserve brand names for og:site_name
  • og:description: A concise hook (55–150 characters) elaborating on the title
  • og:image: Absolute URL to the preview image (Recommended: 1200 x 630 px, 1.91:1 aspect ratio, < 8 MB)
  • og:url: The canonical URL without tracking parameters (utm_*) to consolidate engagement signals
  • og:type: Schema category ("website" for static pages, "article" for blog posts)

Core Twitter Card Elements:

  • twitter:card:and Specifies the card format. The most effective options are:
  • twitter:card: Card format (summary_large_image for full-width banners; summary for compact horizontal thumbnails)
  • twitter:site: The brand's @username
  • twitter:creator: The author's @username
  • twitter:title & twitter:description: Twitter-specific headline and text overrides
  • twitter:image: Absolute image URL displayed in Twitter feeds

Comprehensive Code Implementation

Drop this production-ready boilerplate into the <head> section of your HTML template:

HTML
<head>
  <!-- Standard Meta -->
  <title>Article Title | Brand Name</title>
  <meta name="description" content="A concise summary of your webpage under 150 characters.">
  <!-- Open Graph -->
  <meta property="og:site_name" content="Brand Name">
  <meta property="og:type" content="article">
  <meta property="og:title" content="Article Title Optimized for Social Feeds">
  <meta property="og:description" content="A concise summary of your webpage under 150 characters.">
  <meta property="og:image" content="https://example.com/images/social-banner-1200x630.jpg">
  <meta property="og:image:width" content="1200">
  <meta property="og:image:height" content="630">
  <meta property="og:image:alt" content="Visual description of the banner image">
  <meta property="og:url" content="https://example.com/blog/article-slug">
  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:site" content="@BrandHandle">
  <meta name="twitter:creator" content="@AuthorHandle">
  <meta name="twitter:title" content="Article Title Optimized for Social Feeds">
  <meta name="twitter:description" content="A concise summary of your webpage under 150 characters.">
  <meta name="twitter:image" content="https://example.com/images/social-banner-1200x630.jpg">
  <meta name="twitter:image:alt" content="Visual description of the banner image">
</head>

Setting Up and Configuring Open Graph Tags in WordPress Using Yoast or ACF

You can set up Open Graph (OG) and Twitter tags in WordPress using two primary approaches, depending on your technical setup:

Yoast SEO (Plugin-Based / Standard CMS)

This method is ideal if you're looking for a user-friendly interface that allows authors and editors to customize social titles, descriptions, and preview images for each post without the need for coding.

ACF (Advanced Custom Fields / Code-Based)

This approach is best suited for those using a custom theme or a headless WordPress setup, where you desire full programmatic control over custom fields, metadata output, and dynamic fallbacks.

Method 1: Using Yoast SEO (Standard / GUI Approach)

Yoast automatically generates basic Open Graph and Twitter Card tags by default, using your site's title, featured image, and excerpt. Here’s how to configure global settings and per-post overrides:

Enable Global Social Settings

  • In your WordPress dashboard, go to Yoast SEO > Settings (or Social in older versions)
  • Under Site Features, ensure that both Open Graph data and Twitter card data are toggled ON
  • In the Social Profiles section, add your brand's social media handles (e.g., your X/Twitter @handle, Facebook Page URL, LinkedIn profile). This information populates the `twitter:site` tag and structured schema data
  • In the Social Sharing section (or Content Types > Pages/Posts), upload a Default social share image (1200 x 630 px). This image will serve as a fallback if an editor publishes a post without a designated featured image

Configure Per-Post / Per-Page Metadata

When editing any post or page in the Block or Classic Editor, scroll down to the Yoast SEO meta box located below or beside the editor.

  • Click on the Social tab
  • Here, you will see previews for Facebook (standard Open Graph) and Twitter:
  • Social Title: This overrides `og:title` and `twitter:title` if you need a title different from your SEO title
  • Social Description: This overrides `og:description` and `twitter:description`
  • Social Image: Upload a dedicated image (1200 x 630 px). Use this if your internal featured image has a different aspect ratio that may appear cropped on social feeds

Method 2: Programmatic Setup with Advanced Custom Fields (ACF)

If you are developing a custom WordPress theme (or want to create custom meta boxes without using a comprehensive SEO plugin), you can create specific social fields using ACF and directly inject the tags into `wp_head`.

Step 1: Create Custom Fields in ACF

  • Navigate to ACF > Field Groups > Add New.
  • Name the group: Social Metadata.
  • Set the location rule to: Post Type is equal to Post (and/or Page).
  • Add the following fields:
  •   Field Label: Social Title | Field Name: `og_title` | Type: Text
  •   Field Label: Social Description | Field Name: `og_description` | Type: Textarea
  •   Field Label: Social Image | Field Name: `og_image` | Type: Image (Set Return Value to Image URL)
  •   Field Label: Twitter Card Type | Field Name: `twitter_card_type` | Type: Select (Choices: `summary_large_image`, `summary`)

Step 2: Hook the Tags into (wp_head)

Add the following code to your active theme’s `functions.php` file (or a site-specific custom plugin). This code will pull data from ACF first, then fall back to native WordPress data (featured image, excerpt, post title) if necessary.

functions.php
function custom_acf_social_meta_tags() {
    if (!is_singular()) {
        return;
    }
    global $post;
    $post_id = $post->ID;

    // Title: ACF -> Post Title -> Blog Name
    $title = get_field('og_title', $post_id) ?: get_the_title($post_id);

    // Description: ACF -> Post Excerpt -> Blog Description
    $description = get_field('og_description', $post_id);
    if (!$description) {
        $description = has_excerpt($post_id) ? get_the_excerpt($post_id) : wp_strip_all_tags(wp_trim_words($post->post_content, 25));
    }

    // Image: ACF -> Featured Image -> Fallback Global Image
    $image = get_field('og_image', $post_id);
    if (!$image && has_post_thumbnail($post_id)) {
        $image = get_the_post_thumbnail_url($post_id, 'full');
    }
    if (!$image) {
        $image = 'https://example.com/wp-content/uploads/default-og.jpg'; // Set absolute fallback URL
    }
    $card_type = get_field('twitter_card_type', $post_id) ?: 'summary_large_image';
    $canonical_url = get_permalink($post_id);
    echo "\n<!-- Dynamic Open Graph & Twitter Cards via ACF -->\n";
    echo '<meta property="og:site_name" content="' . esc_attr(get_bloginfo('name')) . '" />' . "\n";
    echo '<meta property="og:type" content="' . (is_single() ? 'article' : 'website') . '" />' . "\n";
    echo '<meta property="og:title" content="' . esc_attr($title) . '" />' . "\n";
    echo '<meta property="og:description" content="' . esc_attr($description) . '" />' . "\n";
    echo '<meta property="og:url" content="' . esc_url($canonical_url) . '" />' . "\n";
    echo '<meta property="og:image" content="' . esc_url($image) . '" />' . "\n";
    echo '<meta name="twitter:card" content="' . esc_attr($card_type) . '" />' . "\n";
    echo '<meta name="twitter:site" content="@BrandHandle" />' . "\n";
    echo '<meta name="twitter:title" content="' . esc_attr($title) . '" />' . "\n";
    echo '<meta name="twitter:description" content="' . esc_attr($description) . '" />' . "\n";
    echo '<meta name="twitter:image" content="' . esc_url($image) . '" />' . "\n";
    echo "<!-- End Social Meta -->\n\n";
}
add_action('wp_head', 'custom_acf_social_meta_tags', 5);

Method 3: Linking ACF directly into Yoast SEO Filters

If Yoast SEO is already installed and you want ACF custom fields to automatically override Yoast's output without printing duplicate tags, add these filters to functions.php:

functions.php (Yoast Filters)
// Override Yoast OG Title with ACF
add_filter('wpseo_opengraph_title', function($title) {
    if (is_singular() && function_exists('get_field')) {
        $acf_title = get_field('og_title');
        return !empty($acf_title) ? $acf_title : $title;
    }
    return $title;
});

// Override Yoast OG Description with ACF
add_filter('wpseo_opengraph_desc', function($desc) {
    if (is_singular() && function_exists('get_field')) {
        $acf_desc = get_field('og_description');
        return !empty($acf_desc) ? $acf_desc : $desc;
    }
    return $desc;
});

// Override Yoast OG Image with ACF
add_filter('wpseo_opengraph_image', function($img) {
    if (is_singular() && function_exists('get_field')) {
        $acf_img = get_field('og_image');
        return !empty($acf_img) ? $acf_img : $img;
    }
    return $img;
});

Method 4: Headless WordPress (ACF + Next.js App Router)

Next.js / TypeScript
import { Metadata } from 'next';

type Props = {
  params: { slug: string };
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const res = await fetch(`https://api.yourdomain.com/wp-json/wp/v2/posts?slug=${params.slug}&_embed`);
  const posts = await res.json();
  const post = posts[0];

  if (!post) return {};

  const title = post.acf?.og_title || post.title.rendered;
  const description = post.acf?.og_description || post.excerpt.rendered.replace(/<[^>]*>?/gm, '');
  const image = post.acf?.og_image || post._embedded?.['wp:featuredmedia']?.[0]?.source_url || 'https://example.com/fallback.jpg';
  const cardType = post.acf?.twitter_card_type || 'summary_large_image';

  return {
    title,
    description,
    openGraph: {
      title,
      description,
      url: `https://yourdomain.com/blog/${params.slug}`,
      siteName: 'YourBrand',
      images: [
        {
          url: image,
          width: 1200,
          height: 630,
          alt: title,
        },
      ],
      type: 'article',
    },
    twitter: {
      card: cardType,
      site: '@YourBrandHandle',
      title,
      description,
      images: [image],
    },
  };
}

Enable Show in REST API in your ACF Field Group settings. In your frontend application (e.g., Next.js 14+), map the ACF fields in generateMetadata:


Verification Note

If you are using both Yoast SEO and custom ACF code, it's important to disable Yoast's social tags by navigating to Yoast SEO > Settings. This step will help prevent duplicate `<meta property="og:*">` tags, which can cause confusion with Facebook and LinkedIn parsers.

After publishing your content, be sure to test the live link using the LinkedIn Post Inspector or Facebook Sharing Debugger. This will allow you to verify that the tags are populating correctly.

Implementation Checklist

[ ] Use absolute URLs (starting with https://) for both `og:url` and all image assets

[ ] Format visual assets to 1200 × 630 pixels with a 1.91:1 aspect ratio

[ ] Keep headlines between 40 and 60 characters to ensure visibility across devices

[ ] Keep descriptions under 150 characters, prioritizing the core value proposition at the beginning

[ ] Include `og:image:alt` and `twitter:image:alt` tags for accessibility and screen reader support

[ ] Test pages with debugging tools before scheduling distribution campaigns

Conclusion

Configuring Open Graph and Twitter Card tags in WordPress significantly affects how your content performs across social media platforms and messaging apps. Without proper metadata, link previews are left to chance, often resulting in broken thumbnails, poorly cropped logos, and arbitrary snippet text that can reduce click-through rates.

You have several options for implementing tags: use Yoast SEO for a no-code, editorial workflow; leverage ACF with custom PHP hooks for complete control at the theme level; or establish an ACF-to-REST API pipeline for modern headless architectures. Regardless of your approach, the goal remains the same:

  • Deliver eye-catching imagery with dimensions of 1200 × 630 pixels, optimized for a 1.91:1 aspect ratio, suitable for feed viewports.
  • Craft engaging, concise headlines (under 60 characters) that are designed for social engagement rather than just focusing on search keyword density.
  • Ensure proper canonical fallback handling so that unpopulated fields never result in empty or broken preview cards.

Once your tags are implemented, remember to include cache invalidation in your publishing and debugging routine. Use tools like the LinkedIn Post Inspector and Meta Sharing Debugger to aid in this process. Fully controlling your social cards ensures that your site projects authority, enhances brand consistency, and maximizes traffic whenever your audience shares your work.

Disclaimer:

The information and tools provided on this website are for general informational and educational purposes only. While we strive to ensure accuracy and reliability, we make no guarantees regarding the completeness, correctness, or usefulness of any content or tools available on this site.

About the Author

Devendra Singh

Devendra Singh is an SEO professional with experience in technical SEO, on-page optimization, keyword research, and website audits. He regularly publishes practical SEO guides and digital marketing tutorials.
Share:

Comments

Post a Comment