DEV Community

nico_lrx
nico_lrx

Posted on

How to Automatically Share Your Wordpress Articles with Buffer and Cron

Wordpress Buffer Cron

For bloggers writing a lot of articles, it's a kind of a headache when it comes to sharing them on Social Media. We usually do it after publishing and then forgot to share it again on a regular basis, hence losing a whole bunch of potential readers.

That's why I decided to automatize the Social Media publications for my Wordpress blog, using Cron and the Buffer API. Cron in Wordpress allows you to schedule time-based tasks. Buffer is a service to schedule posts on Social Media.

Let's set up the new cron job

First, we need to set up the new Wordpress cron job. The cron system comes with default intervals of hourly, twicedaily, and daily. However, it's possible to define your own interval:

// We add a new interval running the task every three hour
add_filter( 'cron_schedules', 'example_add_cron_interval' );
function example_add_cron_interval( $schedules ) {
    $schedules['three_hours'] = array(
        'interval' => 10800,
        'display'  => esc_html__( 'Every Three Hours' ),
    );

    return $schedules;
}

The parameter interval is an integer for the duration in seconds. With this code, you can now use the new cron interval "three_hours".

Then, we need to add the new cron task. We can add a button in our admin menu in order to do that:

function buffer_init_cron() {
    if ( ! wp_next_scheduled( 'buffer_cron_hook' ) ) {
    wp_schedule_event( time(), 'three_hours', 'buffer_cron_hook' );
        echo '<pre>'; print_r( _get_cron_array() ); echo '</pre>'; // to confirm that the new cron job is scheduled
    }
}

function add_buffer_menu_item_cron() {
  // $page_title, $menu_title, $capability, $menu_slug, $callback_function
  add_menu_page(__('Schedule Cron Buffer Posts'), __('Schedule Cron Buffer Posts'), 'manage_options', 'buffer_menu1', 'buffer_init_cron');
}
add_action('admin_menu', 'add_buffer_menu_item_cron');

Pressing the button "Schedule Cron Buffer Posts" in the admin menu will initialize the cron job.

wp_schedule_event takes three parameters: the first time that you want the event to occur, the recurrence (three hours in that case), and the function to call that links the cron to a function to execute. For this last parameter, we need to add this action:

add_action( 'buffer_cron_hook', 'buffer_schedule_posts' );

If you want to be able to manage your cron intervals and cron jobs, you can install the WP Crontrol plugin. This plugin will allow you to create new intervals, to run your cron jobs directly in the admin panel, to create and remove cron jobs.

Create the function to schedule posts with the Buffer API

In the buffer_schedule_posts function we want to get a random post:

        $args = array(
                'post_type' => 'post',
                'orderby'   => 'rand',
                'posts_per_page' => 1,
                );

        $the_query = new WP_Query( $args );

Then, we want to extract the relevant information in order to create the text of the Social Media publication. In my case, I wanted to get the title of the post, the excerpt for the description of Social Media's rich cards, and of course the URL.

    if ( $the_query->have_posts() ) {
            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                $page_title = get_the_title();
                $page_description = get_the_excerpt();
                $link = get_permalink();
                $text = $page_title . " " . $link;
            }
        }

The Buffer API provides an access token. I create a function with the code above in order to return a $fields variable containing the POST parameters needed for the API to run.

    // we get a random pages
    function wpb_rand_posts() {

        $args = array(
                'post_type' => 'post',
                'orderby'   => 'rand',
                'posts_per_page' => 1,
                );

        $the_query = new WP_Query( $args );

        if ( $the_query->have_posts() ) {

            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                $page_title = get_the_title();
                $page_description = get_the_excerpt();
                $link = get_permalink();
                $text = $page_title . " " . $link;

                $fields = "access_token=YOUR_TOKEN&text=" . $text . "&profile_ids[]=YOUR_PROFILE_ID&media[link]=".$link."&media[description]=".$page_description."&now=false";

        }
            return $fields;
            /* Restore original Post Data */
            wp_reset_postdata();
        }
    }

Great, we get a random page with all the information needed for the Social Media publication! One last step is to perform the Buffer API call, using Curl:

    $ch = curl_init();

    $page_fields = wpb_rand_posts();

    curl_setopt($ch, CURLOPT_URL,"https://api.bufferapp.com/1/updates/create.json");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $page_fields);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

    // Receive server response ...
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $server_output = curl_exec($ch);

    curl_close ($ch);

Voilà! We have our buffer_schedule_posts function, running every three hours to publish a post via Buffer. Sit back and relax 😎

Top comments (5)

Collapse
 
drawcard profile image
Drawcard

Thanks for sharing - it's worth noting that WP Cron only runs when a site is visited. But that's probably solved as you log in and write / post more articles 👍

Collapse
 
nicolrx profile image
nico_lrx

I didn't know about that, can you explain more? What do you mean by "is visited", only by the admin or any visitor?

Collapse
 
drawcard profile image
Drawcard • Edited

Sure, it's in the Plugin Handbook at developer.wordpress.org/plugins/cron/

WP-Cron works by: on every page load, a list of scheduled tasks is checked to see what needs to be run. Any tasks scheduled to be run will be run during that page load. WP-Cron does not run constantly as the system cron does; it is only triggered on page load. Scheduling errors could occur if you schedule a task for 2:00PM and no page loads occur until 5:00PM.

I presume from that, 'page load' means either someone visiting your site and requesting a page, or someone logging in and loading an admin page (eg to edit content) in the backend as well.

Thread Thread
 
nicolrx profile image
nico_lrx

Interesting, thanks!

Collapse
 
ann profile image
Ann

WP system's own cron is triggered by the visitor, if there are no sufficient visitors, wp's cron may not be able to run as frequent as webmaster expects.
WordPress users can disable the WP Cron System by adding
define(‘DISABLE_WP_CRON’, true);
to your wp-config.php file, and use server cron or external cron service (like easycron.com).