Auto-posting WordPress posts to Twitter without plugins

Auto-posting to Twitter from WordPress

Introduction

With social media seemingly taking over the world, it is often essential that a website can effectively contribute to client’s social accounts. This generally comes in the form of having new posts being automatically posted to Twitter or Facebook. In this blog I am going to walk through how to auto-post to Twitter without the use of any plugins in WordPress.

There are many plugins which can ultimately achieve this goal, but this unnecessarily adds to the number of installed plugins, and I find many to be rigid. For example, if you want only certain posts being submitted, or if you want to give users the choice to post to separate Twitter accounts, there aren’t many (none that I seen) plugins providing this level of customisability.

Twitter provides a great API to work with. For PHP there are many available libraries to interact with Twitter. I tend to go with Codebird for general ease of use and a great feature-set. There are a few server requirements when using this library, but any decent hosting plan should have these covered.

Download

The first step is to download the library. Go to the Codebird Github repository, switch to the Release branch and click the “Clone or download” button. You can use Git to clone the repository to your system, or download the zip and extract it, up to you; the end-result will be you having the folder on your system.

Downloading the Codebird Twitter library

Rename the folder to “codebird” and move it to your WordPress theme folder. I usually add libraries to an “includes” folder:

wp-content/themes/theme-name/includes/codebird

The “codebird” folder should now contain the “src” and “test” folders, along with the other files from the download. There is only really one file needed here (src/codebird.php), but this is up to you.

Create Twitter App

The next step is to create a Twitter app here. You may need to register if you haven’t already. Creating an App will allow us to authenticate the current Twitter account and enable us to Tweet from it.

Click the “Create New App” button and add the relevant details for your app:

Creating a Twitter application

After the app has been created, go to the “Keys and Access Tokens” tab, everything else can be ignored for now. Click “Create my Access Token”. Take note of the 4 unique keys here:

  • Consumer Key (API Key)
  • Consumer Secret (API Secret)
  • Access Token
  • Access Token Secret

Read and write access should be enabled for default, so leave these as they are.

One thing to be very careful of when copying these keys is that there may be extra spaces in them. This is very easily missed when copying from Twitter, so i’d suggest pasting them into Notepad or similar to strip any extra spaces. Also, do not store these keys in a public repository.

Configuration

It’s now time to get stuck into the actual code to get this working.

I’ll explain what the code is doing before showing it. I’m using the WordPress hook transition_post_hook to check the current status of a post (if it’s a draft for example), and only firing the auto-post function when it changes to a published post.

Open your functions file (create this if it doesn’t already exist):

wp-content/themes/theme-name/functions.php

Add the following:

######################################################################################
##
## Auto-post new articles to Twitter. This uses the Codebird library:
## https://github.com/jublonet/codebird-php/tree/release/3.2.0
##
######################################################################################

// Make this function run whenever it changes from any of these statuses to 'publish':
add_action('auto-draft_to_publish', 'twitter_auto_post', 10, 1);
add_action('draft_to_publish', 'twitter_auto_post', 10, 1);
add_action('future_to_publish', 'twitter_auto_post', 10, 1);
add_action('new_to_publish', 'twitter_auto_post', 10, 1);
add_action('pending_to_publish', 'twitter_auto_post', 10, 1);

Now it’s time to create our function. This is named ‘twitter_auto_post’.

The first action of the function is to grab the ID of the posted article. This will allow us to check the post status and get the information for the Tweet.

Next, we check our database to see if the article has been Tweeted previously using get_post_meta. If it has been previously posted, we will not post it again. This is being checked against a value we will add further into the function, so don’t worry about this too much for now:

function twitter_auto_post() {

    // Get ID of the published post:
    $post_id = get_the_ID();

    // Check to see if this has already been Tweeted
    $posted = get_post_meta($post_id, 'social_twitter_posted', true);

Now that we have determined that the article has not been previously Tweeted, we require the Codebird library.

Replace the keys below with those previously created from the Twitter Application, allowing Codebird to be setup for the Tweet:

// If it hasn't previously been posted, create and post a Tweet:
if ($posted != 'true') {

    // Include Codebird library. Ensure this matches where you have saved it:
    require_once __DIR__ . '/includes/codebird/src/codebird.php';

    // Set your keys. Get these from your created Twitter App:
    $consumer_key = 'replace_with_your_keys';
    $consumer_secret = 'replace_with_your_keys';
    $access_token = 'replace_with_your_keys';
    $access_token_secret = 'replace_with_your_keys';

    // Codebird setup:
    \Codebird\Codebird::setConsumerKey($consumer_key, $consumer_secret);
    $cb = \Codebird\Codebird::getInstance();
    $cb->setToken($access_token, $access_token_secret);

The next step is to actually compose what is to be Tweeted. This can be easily customised, but for this example i’ve went with a simple “New post! Post title – Post link” and an image.

The image section can be left as it is, as this generally never changes so isn’t anything to worry about:

// Get data from the published post:
$post_title = get_the_title($post_id);
$post_image = get_the_post_thumbnail_url($post_id);
$post_link = get_the_permalink($post_id);

// Compose a status using the gathered data:
$status = 'New post! ' . $post_title . ' - ' . $post_link;

// Prepare for image upload:
$media_files = array($post_image);
$media_ids = array();

foreach ($media_files as $file) {
    $reply = $cb->media_upload(array (
        'media' => $file
    ));
    $media_ids[] = $reply->media_id_string;
}
$media_ids = implode(',', $media_ids);

…and finally! It’s time to put the tweet together and send it to Twitter. This comes in the form of an array which contains our previously created status and the post image:

// Send Tweet with image and status:
$reply = $cb->statuses_update(array (
    'status'    => $status,
    'media_ids' => $media_ids
));

The final piece of the puzzle is to log if the Tweet was successful or not. This is important as it will prevent duplicate Tweets. It will also log any errors that may have occurred, allowing easy debugging of failed Tweets (I have yet to see any fail with this function). There will be a meta key stored in the database in the ‘wp_postmeta’ table with the key ‘social_twitter_posted’, with either the value ‘true’ or the error received.

        // Check status of Tweet submission:
        if ($reply->httpstatus == 200) {
            // Add database entry showing that the Tweet was sucessful:
            add_post_meta($post_id, 'social_twitter_posted', 'true', true);
        } else {
            // Add database entry showing error details if it wasn't successful:
            add_post_meta($post_id, 'social_twitter_posted', $reply->httpstatus, true);
        }

    } else {
        // Tweet has already been posted. This will prevent it being posted again:
        return;
    }

}

Go check your Twitter account and you should see a shiny new Tweet! It should contain the title, link and image of the post which was just published in WordPress. See the image below for an example of this:

Auto-posted Tweet example

Full example below:

######################################################################################
##
## Auto-post new articles to Twitter. This uses the Codebird library:
## https://github.com/jublonet/codebird-php/tree/release/3.2.0
##
######################################################################################

// Make this function run whenever it changes from any of these statuses to 'publish':
add_action('auto-draft_to_publish', 'twitter_auto_post', 10, 1);
add_action('draft_to_publish', 'twitter_auto_post', 10, 1);
add_action('future_to_publish', 'twitter_auto_post', 10, 1);
add_action('new_to_publish', 'twitter_auto_post', 10, 1);
add_action('pending_to_publish', 'twitter_auto_post', 10, 1);

function twitter_auto_post() {

    // Get ID of the published post:
    $post_id = get_the_ID();

    // Check to see if this has already been Tweeted
    $posted = get_post_meta($post_id, 'social_twitter_posted', true);

    // If it hasn't previously been posted, create and post a Tweet:
    if ($posted != 'true') {

        // Include Codebird library. Ensure this matches where you have saved it:
        require_once __DIR__ . '/includes/codebird/src/codebird.php';

        // Set your keys. Get these from your created Twitter App:
        $consumer_key = 'replace_with_your_keys';
        $consumer_secret = 'replace_with_your_keys';
        $access_token = 'replace_with_your_keys';
        $access_token_secret = 'replace_with_your_keys';

        // Codebird setup:
        \Codebird\Codebird::setConsumerKey($consumer_key, $consumer_secret);
        $cb = \Codebird\Codebird::getInstance();
        $cb->setToken($access_token, $access_token_secret);

        // Get data from the published post:
        $post_title = get_the_title($post_id);
        $post_image = get_the_post_thumbnail_url($post_id);
        $post_link = get_the_permalink($post_id);

        // Compose a status using the gathered data:
        $status = 'New post! ' . $post_title . ' - ' . $post_link;

        // Prepare for image upload:
        $media_files = array($post_image);
        $media_ids = array();

        foreach ($media_files as $file) {
            $reply = $cb->media_upload(array (
                'media' => $file
            ));
            $media_ids[] = $reply->media_id_string;
        }
        $media_ids = implode(',', $media_ids);

        // Send Tweet with image and status:
        $reply = $cb->statuses_update(array (
            'status'    => $status,
            'media_ids' => $media_ids
        ));

        // Check status of Tweet submission:
        if ($reply->httpstatus == 200) {
            // Add database entry showing that the Tweet was sucessful:
            add_post_meta($post_id, 'social_twitter_posted', 'true', true);
        } else {
            // Add database entry showing error details if it wasn't successful:
            add_post_meta($post_id, 'social_twitter_posted', $reply->httpstatus, true);
        }

    } else {
        // Tweet has already been posted. This will prevent it being posted again:
        return;
    }

}

Codebird serves as an excellent library for effectively auto-posting WordPress posts to Twitter. This function can also be customised in any number of ways, allowing great flexibility for any client’s needs. If you have any questions or issues feel free to get in contact with me 🙂

Links

Posted by Steven Cotterill - 27/05/2018

Want to work with us on a project? Get in touch!