How To Create WordPress Twitter Feed Plugin

Needless to say, how popular Twitter is? A lot of websites are showing their latest tweets to users. Normally, these tweets are either placed in the sidebar or in a footer. In today’s post, we will create a simple WordPress plugin that displays the latest tweets wherever you want. We are going to create a shortcode which can place anywhere on your site.

How To Create A Plugin

Creating a plugin for WordPress is not rocket science. A man who knows PHP and WordPress can easily create the plugin. For our task, I am creating a folder name ‘twitter-api’ under the ‘wp-content/plugins’ directory.

Next, I create ‘twitter-api.php’ and place it under the ‘plugins/twitter-api’ folder. Our plugin file ‘twitter-api.php’ needs some comments, so I add it in the below format.

/*
Plugin Name: Twitter API
Plugin URI: https://artisansweb.net
Description: This plugin will fetch your latest tweets and display it using shortcode [tweets]
Version: 1.0
Author: Sajid
Author URI: https://artisansweb.net
License: GPLv2 or later
Text Domain: artisansweb
*/

After adding the above comment, our plugin will appear on the plugins page from where we can activate it. But as we did not write any code, it just gets activated but doesn’t do anything. We will add a lot of code to our plugin. But for now, we just create the basic structure of our plugin.

class Twitter_API {
    public function __construct() {
 
    }
}

To avoid direct access to our plugin’s PHP files we should add the below line after our plugin’s comment.

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

Install Twitter PHP Library

Twitter provides REST APIs for developers. For our plugin, we are using a popular library for Twitter which is built in PHP. Here is the git-hub URL for the library – https://github.com/abraham/twitteroauth

To install this library I will open a command prompt in my ‘plugins/twitter-api’ folder and run the below command.

composer require abraham/twitteroauth

After installing the library, I will place the below lines in our ‘twitter-api.php’ file.

require('vendor/autoload.php');
use Abraham\TwitterOAuth\TwitterOAuth;

Now, it’s time to register our Twitter Application. To create an application, go to Twitter Apps and follow the below steps.

  • Click the button ‘Create New App’.
  • Fill up the Name, Description, and Website fields.
  • Accept the agreement and click the button ‘Create your Twitter application’.
  • On the next page, click on the tab ‘Keys and Access Tokens’. Under this tab, you will find your Consumer Key and Consumer Secret. Copy these details and store them in a safe place.
  • Under the same tab, you will see the section ‘Your Access Token’. Click on the button ‘Create Access Token’.
  • At this step, copy your Access Token and Access Token Secret. Keep these details safe.

We have created our Twitter Application and also we are ready with our API keys. To use these details in our plugin we first need to store it. For this, we are creating an options page for our plugin. So I add the below code to our file.

function __construct() {
    add_action( 'admin_menu', array($this, 'ta_plugin_menu') );
}
 
function ta_plugin_menu() {
    add_options_page('Twitter API', 'Twitter API', 'manage_options', 'twitter_api', array($this, 'ta_settings_page'));
}
 
function ta_settings_page() {
    require_once('inc/ta-settings.php');    
}

Above code will add our menu called ‘Twitter API’ under Settings on a dashboard. At this stage, we need to create the ‘inc’ directory and place a ‘ta-setting.php’ file in it.

In the ‘ta-setting.php’ file we will give the option to store our Twitter API details. I am adding the below code in this file. We are fetching value(which we store in the next step) for each field from the database.

<h1><?php _e('Twitter Information', 'artisansweb'); ?></h1>
<form method="post">
    <table class="form-table">
        <tbody>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Consumer Key', 'artisansweb'); ?></label></th>
                <td><input name="ta_consumer_key" id="ta_consumer_key" value="<?php if(get_option('ta_consumer_key')) echo get_option('ta_consumer_key'); ?>" class="regular-text" type="text"></td>
            </tr>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Consumer Secret', 'artisansweb'); ?></label></th>
                <td><input name="ta_consumer_secret" id="ta_consumer_secret" value="<?php if(get_option('ta_consumer_secret')) echo get_option('ta_consumer_secret'); ?>" class="regular-text" type="text"></td>
            </tr>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Access Token', 'artisansweb'); ?></label></th>
                <td><input name="ta_access_token" id="ta_access_token" value="<?php if(get_option('ta_access_token')) echo get_option('ta_access_token'); ?>" class="regular-text" type="text"></td>
            </tr>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Access Token Secret', 'artisansweb'); ?></label></th>
                <td><input name="ta_access_token_secret" id="ta_access_token_secret" value="<?php if(get_option('ta_access_token_secret')) echo get_option('ta_access_token_secret'); ?>" class="regular-text" type="text"></td>
            </tr>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Number of Tweets', 'artisansweb'); ?></label></th>
                <td><input name="ta_no_of_tweets" id="ta_no_of_tweets" value="<?php if(get_option('ta_no_of_tweets')) echo get_option('ta_no_of_tweets'); ?>" class="regular-text" type="number"></td>
            </tr>
        </tbody>
    </table>
    <p class="submit">
        <input name="ta-submit" id="submit" class="button button-primary" value="<?php _e('Save Changes', 'artisansweb'); ?>" type="submit">
    </p>
</form>

On this page, we enter the API details which we need to save in the database. So I used the ‘init’ action and add submit logic in the callback function.

add_action('init', array($this, 'ta_submit_callback')); //add this code in constructor
 
function submit_callback() {
    if (isset($_POST['ta-submit'])) {
        update_option( 'ta_consumer_key', $_POST['ta_consumer_key'] );
        update_option( 'ta_consumer_secret', $_POST['ta_consumer_secret'] );
        update_option( 'ta_access_token', $_POST['ta_access_token'] );
        update_option( 'ta_access_token_secret', $_POST['ta_access_token_secret'] );
        update_option( 'ta_no_of_tweets', $_POST['ta_no_of_tweets'] );
    }
}

At this stage, we have completed with back-end settings required for our plugin. Now, we are going to the front end where we need to display the latest tweets. We are creating a shortcode so we can display tweets wherever we want just by placing our shortcode. In the constructor, I will place it below the line of code.

//add this code in constructor
add_shortcode('tweets', array($this, 'ta_latest_tweets'));
 
if(get_option('ta_consumer_key')) {
    $this->consumer_key = get_option('ta_consumer_key');
}
if(get_option('ta_consumer_secret')) {
    $this->consumer_secret = get_option('ta_consumer_secret');
}
if(get_option('ta_access_token')) {
    $this->access_token = get_option('ta_access_token');
}
if(get_option('ta_access_token_secret')) {
    $this->access_token_secret = get_option('ta_access_token_secret');
}
$this->ta_no_of_tweets = get_option('ta_no_of_tweets') ? get_option('ta_no_of_tweets') : 3;

We are also fetching API details in the constructor. We should declare class variables like below.

protected $consumer_key = '', $consumer_secret = '', $access_token = '', $access_token_secret = '', $ta_no_of_tweets;

Next, we should define our shortcode callback function.

function ta_latest_tweets() {
    $connection = new TwitterOAuth($this->consumer_key, $this->consumer_secret, $this->access_token, $this->access_token_secret);
 
    $arr_tweets = $connection->get("statuses/user_timeline", ["count" => ($this->ta_no_of_tweets), "exclude_replies" => true]);
 
    if ($arr_tweets && !empty($arr_tweets)) {
        ?>
        <ul class="tweet-wrap">
            <?php
            foreach ($arr_tweets as $tweet) {
                ?>
                <li>
                    <div>
                        <img src="<?php echo $tweet->user->profile_image_url; ?>">
                        <strong><?php echo $tweet->user->name ?></strong> @<span><?php echo $tweet->user->screen_name; ?></span>
                    </div>
                    <p><?php echo $tweet->text; ?></p>
                </li>
                <?php
            }
            ?>
        </ul>
        <?php
    }
}

We are adding a little bit of GUI for our tweet listing. So I add the CSS file in the following way.

add_action('wp_enqueue_scripts', array($this, 'ta_include_css')); //add it in constructor
 
function ta_include_css() {
    wp_register_style( "ta-custom-style", plugins_url('/twitter-api') . "/css/custom.css", array(), false, "all" );
    wp_enqueue_style( "ta-custom-style" );
}

In my CSS file, I add the below properties for the class ‘tweet-wrap’. If you wish you can add more CSS as per your need.

.tweet-wrap{
    width: 300px;
    list-style-type: none;
}

That’s all, we are completed with our plugin which displays the latest tweets. You can download a zip of a plugin by clicking the link ‘Get Plugin Code’ below.

Get Plugin Code

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *