# Basic Open Graph and Twitter Card Tags

> Adds Open Graph and Twitter Card meta tags (title, description, image, URL) so links shared on social networks show a proper preview. Skipped when an SEO plugin is active.

- Type: PHP
- Runs: Frontend only
- Category: [SEO](https://wpide.com/library/category/seo/)
- Tags: seo, open-graph, social, twitter
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/open-graph-tags/

## Code

```php
add_action( 'wp_head', function () {
    if ( defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'AIOSEO_VERSION' ) || defined( 'THE_SEO_FRAMEWORK_VERSION' ) || defined( 'SEOPRESS_VERSION' ) ) {
        return;
    }

    $tags = array(
        'og:site_name' => get_bloginfo( 'name' ),
        'og:locale'    => get_locale(),
    );

    if ( is_singular() ) {
        $post                    = get_queried_object();
        $tags['og:type']         = 'article';
        $tags['og:title']        = get_the_title( $post );
        $tags['og:url']          = get_permalink( $post );
        $tags['og:description']  = has_excerpt( $post ) ? $post->post_excerpt : wp_trim_words( excerpt_remove_blocks( strip_shortcodes( $post->post_content ) ), 30, '' );

        if ( has_post_thumbnail( $post ) ) {
            $tags['og:image'] = get_the_post_thumbnail_url( $post, 'large' );
        }
    } else {
        $tags['og:type']        = 'website';
        $tags['og:title']       = wp_get_document_title();
        $tags['og:description'] = get_bloginfo( 'description' );

        if ( is_front_page() ) {
            $tags['og:url'] = home_url( '/' );
        }
    }

    if ( empty( $tags['og:image'] ) && has_site_icon() ) {
        $tags['og:image'] = get_site_icon_url( 512 );
    }

    foreach ( $tags as $property => $value ) {
        $value = trim( wp_strip_all_tags( (string) $value ) );

        if ( '' === $value ) {
            continue;
        }

        $is_url = in_array( $property, array( 'og:url', 'og:image' ), true );
        printf( "<meta property=\"%s\" content=\"%s\" />\n", esc_attr( $property ), $is_url ? esc_url( $value ) : esc_attr( $value ) );
    }

    printf( "<meta name=\"twitter:card\" content=\"%s\" />\n", empty( $tags['og:image'] ) ? 'summary' : 'summary_large_image' );
}, 5 );
```

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Basic Open Graph and Twitter Card Tags" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
