WordPress Code to Bulk Update Twitter.com URLs to X.com
So it finally happened; all Twitter.com links redirect to X.com.
I don't link to Twitter much as it is, but I started seeing a handful of these links pop up in my broken link checker and I really didn't want to update all of them by hand, so here we are: I created a script that does this for you.
Here's the code; simply drop this at the bottom of your functions.php file of your WordPress theme directory, and it handles the rest:
// Replace all hyperlinks to Twitter.com with X.com
function replace_twitter_url( $buffer ) {
return str_replace( 'https://twitter.com/', 'https://x.com/', $buffer );
}
function start_twitter_buffer() {
ob_start( 'replace_twitter_url' );
}
add_action( 'template_redirect', 'start_twitter_buffer' );
Note: This won't edit your links in the WordPress post editor or in your database, but it will edit them on your public-facing site. That also makes this change easily reversible, if you decide you need to undo this for whatever reason. That makes this solution far less risky than a bulk database operation.
Is this the best solution? For most, probably. Especially if you have hundreds or thousands of posts across multiple websites like me.
But if you need to be linking to Twitter.com still for some reason, it could cause issues. Example, if you have a post that says "https://twitter.com/ was the old URL but it became X.com" then it would be changed to "https://x.com/ was the old URL but it became X.com". Obviously that's not what you want.
I had to actually exclude this page in the start_twitter_buffer() function above, just so that didn't happen in this post and so I could share this code.
If you want to do something similar, you'd just replace that function with something like this, which excludes any URLs containing /code/ (change as needed):
function start_twitter_buffer() {
if (strpos($_SERVER['REQUEST_URI'], '/code/') === false) {
ob_start('replace_twitter_url');
}
}
Or if you wanted to exclude specific posts/pages, you could do something like this (replace the excluded IDs below with the real IDs of your posts/pages):
function start_twitter_buffer() {
if (is_singular()) {
$excluded_ids = array(123, 456, 789);
$current_id = get_queried_object_id();
if (in_array($current_id, $excluded_ids)) {
return;
}
}
ob_start('replace_twitter_url');
}
That's pretty much it. Now all of my links (and hopefully yours) are updated to avoid the redirect chain and keep my broken link checker from flagging dozens of Twitter.com URLs.
Did this help you? Questions for me? Please share with me in the comments below!
Comments