How to Easily Embed Tweets in WordPress Posts and Pages

Home » Snippets » How to Easily Embed Tweets in WordPress Posts and Pages

Created with:



Creator: WPTurbo Team

Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project

Have you ever wanted to embed a tweet on your WordPress website? Embedding tweets can be a great way to share social media content with your website visitors, and it’s also a way to add credibility to your content by including user-generated content. In this article, we’ll show you how to easily embed tweets in your WordPress posts and pages using a few simple methods. So, let’s get started!

					function wpturbo_embed_tweet($atts, $content = null) {
        'id' => '',
        'align' => ''
    ), $atts));

    if (!$id) {
        return '';

    $tweet_html = '';
    $tweet = wp_oembed_get( ''. $id );
    if (!empty($tweet)) {
        if ($align == 'center') {
            $tweet_html .= "<div style='text-align: center;'>";

        $tweet_html .= $tweet;

        if ($align == 'center') {
            $tweet_html .= "</div>";

    return $tweet_html;
add_shortcode('tweet', 'wpturbo_embed_tweet');

This code enables users to embed tweets in their WordPress sites using a shortcode. The shortcode we will use for this purpose is [tweet].

The first part of the code defines a function called wpturbo_embed_tweet, which accepts two arguments: $atts and $content. It then uses the extract() function to retrieve the attributes passed in the shortcode. In this case, there are two attributes: id and align.

The id attribute is used to specify the tweet ID, while the align attribute is used to specify the alignment of the embedded tweet.

Next, we have an if statement that checks whether the id attribute has a value. If not, the function returns an empty string.

The next step is to get the HTML code for the tweet. This is done using the wp_oembed_get() function, which is a handy function in WordPress that retrieves the HTML required to embed a resource from oEmbed providers like Twitter. We pass in the tweet’s URL, along with its ID.

If the tweet HTML is not empty, the function will check if the $align variable is set to center. If so, it adds a div element with a text-align: center style option for center alignment of the tweet.

The tweet’s HTML code is appended to $tweet_html, which is then returned at the end of the function.

Finally, we hook this function into the WordPress system using the add_shortcode() function. This enables us to use the [tweet] shortcode wherever we need to embed a tweet on our WordPress site. We pass in the name of our shortcode ("tweet") and the name of our function ("wpturbo_embed_tweet") as arguments for the add_shortcode() function.

Register an account to save your snippets or go Pro to get more features.