# Linking X (Twitter) usernames on WordPress posts automatically

> Automatically turn @usernames in your WordPress posts into links to X (Twitter) profiles with a PHP snippet.

Source: https://helpcenter.ruachost.com/wordpress/guides/linking-x-twitter-usernames-on-wordpress-posts-automatically/

If you frequently mention Twitter usernames in your WordPress posts, you can configure WordPress to automatically link them to their respective Twitter profiles. On **ruachost.com**, this can be done with a simple PHP snippet added to your theme.

## Why Enable Automatic Linking?

- Saves time by avoiding manual hyperlinking.
- Ensures consistency across posts and comments.
- Improves user engagement by directing readers to Twitter profiles.

## Steps to Implement Automatic Linking

1. **Log in to WordPress** with an administrator account.
2. In the dashboard, go to **Appearance → Theme Editor**.
3. Select your active theme and open the **functions.php** file.
4. Add the following code snippet:

   ```
   // Automatically link Twitter usernames in posts and comments
   function add_twitter_links($content) {
       $pattern = '/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/';
       $replacement = '$1<a href="https://twitter.com/$2" target="_blank">@$2</a>';
       return preg_replace($pattern, $replacement, $content);
   }
   add_filter('the_content', 'add_twitter_links');
   add_filter('comment_text', 'add_twitter_links');
   ```
5. Click **Update File** to save changes.
6. Test by writing a post or comment with a Twitter handle (e.g., `@ruachost`).

✅ WordPress will automatically convert it into a clickable link pointing to the Twitter profile.

## Important Notes

- Always back up your theme files before editing.
- Use a **child theme** to preserve changes during updates.
- This method works for both posts and comments.
- Ensure usernames are valid Twitter handles to avoid broken links.
