X (Twitter) Handle Meta Tags
Adds twitter:site with your brand's X handle to every page, and twitter:creator with the author's handle on posts, so shared links credit the right accounts.
Opens WPIDE on
Code
// Your site's X handle, with the @.
$wpide_x_site_handle = '@yourbrand';
add_action( 'wp_head', function () use ( $wpide_x_site_handle ) {
if ( '' !== trim( $wpide_x_site_handle ) ) {
echo '<meta name="twitter:site" content="' . esc_attr( $wpide_x_site_handle ) . '" />' . "\n";
}
if ( is_singular( 'post' ) ) {
$handle = trim( (string) get_the_author_meta( 'twitter', (int) get_queried_object()->post_author ) );
if ( '' !== $handle ) {
$handle = '@' . ltrim( preg_replace( '#^https?://(www\.)?(twitter|x)\.com/#i', '', $handle ), '@/' );
echo '<meta name="twitter:creator" content="' . esc_attr( $handle ) . '" />' . "\n";
}
}
}, 6 );
Notes
The author handle is read from a user meta field named twitter; leave it empty and only the site handle is used.
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.