How to Create a WordPress Plugin for Facebook Open Graph Tags

Публикувано на 07.05.2017
How to Create a WordPress Plugin for Facebook Open Graph Tags

Introduction

Today we’ll create a WordPress plugin that automatically adds Facebook Open Graph Tags to your site.
These tags help Facebook display your shared links correctly — with proper title, description, and image.


Facebook Crawler

Without Open Graph tags, the Facebook crawler scans your page and picks whatever it finds.
With our plugin, we’ll tell it exactly what to show, ensuring consistent and professional-looking link previews.


Recommended Image Sizes

Use the following image sizes for best results:

  • High resolution: 1200 × 630 px

  • Low resolution: 600 × 315 px

  • Minimum: 200 × 200 px (below this, the debugger will show an error).


Setup

Before we write the code, let’s create the basics — a folder in wp-content/plugins and a file called facebook-og-tags.php.
If you don’t remember how, check the article “How to Create a WordPress Plugin That Displays Hello World.”


Plugin Code

Paste the following code into your plugin file:

add_action('wp_head', 'cw_facebook_tags');

function cw_facebook_tags() {

    if (is_single() || is_page() || is_home()) {
        ?>
        <meta property="og:title" content="<?php the_title() ?>" />
        <meta property="og:site_name" content="<?php bloginfo('name') ?>" />
        <meta property="og:url" content="<?php the_permalink() ?>" />

        <meta property="og:description" content="<?php $post = get_post($post); $content = substr($post->post_content, 0, 300);
        echo htmlspecialchars($content, ENT_COMPAT, 'ISO-8859-1', true);
        ?>" />

        <meta property="og:type" content="<?php if (is_home() || is_page()) { echo 'website'; } else { echo 'article'; } ?>" />

        <?php if (has_post_thumbnail()) : $image = wp_get_attachment_image_src(get_post_thumbnail_id(), 'large'); ?>
            <meta property="og:image" content="<?php echo $image[0]; ?>"/>
        <?php endif; ?>

        <?php
    }
}

This function checks whether the current page is a single post, a static page, or the homepage, and inserts all necessary Open Graph tags dynamically.


Conclusion

Now you have a working WordPress plugin that automatically generates Facebook Open Graph tags.
You can extend it to manually set og:title or og:description fields for more control — the expanded version is available on GitHub.