Automatically post to social media from WordPress

This article shows you how to automatically post to social media networks such as Facebook and Twitter when a WordPress post is published. Guiding you through the process of connecting to Facebook Opengraph and Twitter API to post status messages.

The code in this article used to auto post to social media can be either added to a WordPress plugin or theme.

How to Automatically post to social media when publishing content in WordPress

Composer is used to install the TwitterOAuth dependency and expect that you have composer installed on your development server, you can however download and include the library manually from github abraham/twitteroauth.

To start with initialize composer the current directory if you have not already, the init command will interactively ask you to fill in some fields before creating the composer.json file.

composer init

Install the TwitterOAuth library using composer require, to handle OAuth authentication with the twitter API.

composer require abraham/twitteroauth

With composer setup we need to include it in our project, do this by requiring ‘vendor/autoload.php’, this will allow access to any dependencies installed by composer.

Start by scaffolding all the required functions to automatically post to social media as shown below, we will hook into the wordpress transition_post_status to capture when a WordPress post is published via our jcsp_on_post_published function, within this function we need to first make sure we are monitoring only the post_type we require (in this example it is looking for posts), we then check to see if the new post_status is ‘publish’, and that the previous post_status was not. If this is correct we trigger our auto post function jcas_auto_post.

<?php
require_once 'vendor/autoload.php';

function jcsp_post_to_facebook($message, $link = '')
{
    // TODO: send facebook status
}

function jcsp_post_to_twitter($message, $link = '')
{
    // TODO: create twitter tweet
}

function jcsp_auto_post($post)
{
    // TODO: 1. Generate message
    // TODO: 2. Send message to each social network once
}

function jcsp_on_post_published($new_status, $old_status, $post)
{
    // skip if not post
    if (get_post_type($post) !== 'post') {
        return;
    }

    // skip if post is not being published
    if ($new_status === $old_status || $new_status !== 'publish') {
        return;
    }

    jcsp_auto_post($post);
}

function jcsp_init()
{
    add_action('transition_post_status', 'jcsp_on_post_published', 10, 3);
}

add_action('plugins_loaded', 'jcsp_init');

Once a post has been published in WordPress we need to generate a status message and link that will be sent to each social media network, in this example we are just using the permalink and post title but this can easily be cusomized if required.

Using post meta data we check to see if a shared flag has already been set per social network (yes = sent, no = failed), if not set we trigger the auto posting of our message to that social network, if posted successfully we then flag the result so that it will not be posted multiple times.

function jcsp_auto_post($post)
{
    // Generate message
    $message = get_the_title($post);
    $link = get_permalink($post);

    // Share to FB
    if (get_post_meta($post->ID, '_jcsp_share_facebook', true) !== 'yes') {
        $result = jcsp_post_to_facebook($message, $link);
        if ($result) {
            update_post_meta($post->ID, '_jcsp_share_facebook', 'yes');
        } else {
            update_post_meta($post->ID, '_jcsp_share_facebook', 'no');
        }
    }

    // Share to Twitter
    if (get_post_meta($post->ID, '_jcsp_share_twitter', true) !== 'yes') {
        $result = jcsp_post_to_twitter($message, $link);
        if ($result) {
            update_post_meta($post->ID, '_jcsp_share_twitter', 'yes');
        } else {
            update_post_meta($post->ID, '_jcsp_share_twitter', 'no');
        }
    }
}

To create the jcsp_post_to_facebook and jcsp_post_to_twitter functions we need to get have access to their developer portals as shown in the following sections.

Automatically post to facebook from WordPress

To automatically post to facebook from WordPress we need to have a facebook developer account and the ability to create facebook apps, this is used to allow access to the facebook opengraph api and generate an Access token.

Create Facebook Application

Visit https://developers.facebook.com/ and create a developer account if not already, once registered start the process of creating a new app. In this example i am posting to a Facebook page so i have chosen the app type of Business.

Fill out the app details such as display name, contact email and set the apps purpose to “Yourself or your own business”, submitting the app creation form by clicking create app.

With the Facebook app created, we need to get the App ID and Secret, this can be done by clicking on the App and going to Settings > Basic where you can see the APP ID, And App Secret fields.

Generate Non expiring Facebook Access Token

Generate an basic access token via Facebook Opengraph Explorer , Select the Facebook app, add pages_read_engagement and pages_manage_posts permissions, with all settings filled out click Generate Access Token, this will allow you to select the profile or page you wish to link.

You could use this access token, but if you use Facebooks access token debugger: https://developers.facebook.com/tools/debug/accesstoken/ , you will see that it will expire in an hour which is not ideal for our use since we do not want to have to generate a new one every time we wish to post. Click the button at the bottom of the page labelled “Extend Access Token”, keep a copy of this newly generated access token should not expiry.

Publish content using Facebook API

Once we have the access token setup and all the information we need, we can new create a new facebook post via php using the following code, making sure to populate the page_id, access_token, app_secret variables.

function jcsp_post_to_facebook($message, $link = '')
{
    $page_id = '';
    $access_token = '';
    $app_secret = '';

    return wp_remote_post('https://graph.facebook.com/v2.10/' . $page_id . '/feed', [
        'body' => [
            'message' => $message,
            'link' => $link,
            'access_token' => $access_token,
            'appsecret_proof' => hash_hmac('sha256', $access_token, $app_secret),
        ]
    ]);
}

Automatically post to Twitter from WordPress

To automatically post to twitter from WordPress we need to have a twitter developer account and the ability to create twitter apps, this is used to allow access and authenticate with the twitter api.

Create Twitter Application and Generate Access Credentials

Head over to developer.twitter.com and apply for a developer account, this should be a case of filling out all the reqired fields.

Once complete you should be able to visit the developer portal and create your first app, when you have created your app, click on the app settings and make sure the permissions are Read and Write.

Now with your app created click on the Keys and Tokens section and generate a new Access Token and Secret with Read and Write permissions.

Publish content using Twitter API

Once we have the access token setup and all the inforamtion we need, we can now create a new tweet via php using the following code, this uses the TwitterOAuth library that we previously installed with composer to authenticate our request.

Unlike the facebook example there i no seperate section for the post permalink, instead we add it onto the end of the message.

function jcsp_post_to_twitter($message, $link = '')
{
    $consumerKey = '';
    $consumerSecret = '';
    $oauthToken = '';
    $oauthTokenSecret = '';

    $twitter = new Abraham\TwitterOAuth\TwitterOAuth($consumerKey, $consumerSecret, $oauthToken, $oauthTokenSecret);

    $url = 'statuses/update';
    $status = !empty($link) ? $message . ' ' . $link : $message;
    return $twitter->post($url, [
        'status' => $status,
        'trim_user' => true
    ]);
}

Conclusion

In this article we covered how to detect when a WordPress post is published, and using post metadata to store a flag which can be checked to see if it is has previosuly been ran allowing us to trigger an event that will only be ran once.

We also touched on how to create a facebook app to allow access to facebook opengraph api and extending the life of an access token to not expire, using these access details to automatically post to facebook from WordPress.

Next we covered how to create a twitter app to allow access to Twitters API, using these access details to auto post to twitter from WordPress.

In the end we created a very basic example showing how to automatically post to social media accounts when a wordpress post is published, this example is a base that can easily be extended to enable / disable on specific posts or post types, even extending what social networks are posted too.

Leave a Reply

Fields marked with an * are required to post a comment