We’ve previously discussed how to embed tweets in WordPress. The embeds feature allow us to directly embed/post a tweet in WordPress by just placing the tweet’s URL in the editor. Just make sure that the URL is placed on its own line. Under the hood, WordPress retrieves the tweet via oEmbed.
The above method works great, but by default, tweets are left aligned. What if you want to center align a tweet in WordPress? If you try to center align that line just as you do with text then you’ll just be able to see the URL centered, and the tweet will just disappear.
That’s where we can use the oembed_result filter to modify the code. Just add the below code to your functions.php file and see the magic happen.
add_filter('oembed_result','twitter_no_width',10,3); function twitter_no_width($html, $url, $args) { if (false !== strpos($url, 'twitter.com')) { $html = str_replace('class="twitter-tweet"','class="twitter-tweet tw-align-center"',$html); $html = str_replace('width="550"','',$html); } return $html; }
But wait; there’s more. After adding this code to functions.php, you won’t be instantly able to see the change in existing post and that’s because WordPress caches the oembed_result. The HTML is retrieved and stored only once, until the cache is cleared.
That’s why you’ll now need to edit the post and then click on the “Update” button without making any changes to it. This will retrieve the HTML and updates the code.
Now check out the front-end and voila, your embedded tweet will be centered. Just make sure that you edit every post if you want them to be centered.
Modified code based on Otto’s method.
I followed this tutorial. And upon saving, got this:
Parse error: syntax error, unexpected T_FUNCTION in /home/mrsblunder/mrsblunder.com/wp-content/themes/origin/functions.php on line 336
It seems you have entered the code at the wrong place. Try placing the code at the end of the functions.php file. I have tested it with default theme and it works.
I just put .twitter-tweer{ margin: auto; } on my child’s theme css file then problem solved.