How to Automatically Share Your Wordpress Articles with Buffer and Cron
Tags: wordpress, php, cron, socialmedia
Published: 2019-02-18 12:30:12

---
title: How to Automatically Share Your Wordpress Articles with Buffer and Cron
published: true
description: A tutorial for Wordpress blog's owners to automatize their Social Media publications using Cron and the Buffer API.
tags: wordpress,php,cron,social media
---

![Wordpress Buffer Cron](https://thepracticaldev.s3.amazonaws.com/i/2ol73s93ufo8lpdiw531.png)

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](https://codex.wordpress.org/Function_Reference/wp_cron) and [the Buffer API](https://buffer.com/developers/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](https://wordpress.org/plugins/wp-crontrol/). 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](https://buffer.com/developers/api/oauth). 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 😎