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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.