Quantcast
Channel: DQuinn.net
Viewing all articles
Browse latest Browse all 148

Automating Scheduled Posts in WordPress to Buffer Social Media Profiles

$
0
0

WordPress to Buffer app plugins just don't cut it. Get fine-tuned control over your sharing text and images when queuing posts on Buffer.

Posted on June 5, 2017 in WordPress

My favorite app for pushing new posts to social media is still Buffer, because it lets you manage all your outgoing content in one central location, and schedules each post to be published in a queue that shares your posts to social platforms at a time that’s best for each platform—where “best” means when the platform is most heavily trafficked.

This way, I can schedule or publish posts at whatever time, and later get them promoted on my social platforms at the optimal time. The only problem is bridging the gap between WordPress and Buffer.

There are lots of WordPress plugins that purport to do the job, but all of them fall short of features in one way or another. So I decided to write some code for WordPress that can post to Buffer plugin-free. To be clear, this is what we want to accomplish:

  • Whenever a scheduled post is published or whenever a post is published, we want it to be loaded into the Buffer queue, on all our social accounts connected to Buffer;
  • We want to be set some default sharing meta, but we also want to be able to override that meta on a per-post basis;
  • Posts that have already been sent out to Buffer shouldn’t get re-Buffered if they’ve already been sent, and we should be able to opt-out posts manually if we want.

You’ll need two things to get started: Advanced Custom Fields to build the Dashboard interface, and a single PHP file, the bufferapp-php library, from thewebguy.

Creating Buffer Settings

First we’ll want to create a panel in the Edit Screen that lets you specify specific sharing information and lock the post from being sent to Buffer manually:

With ACF, make three fields in a Buffer Settings field group:

  • Text type called “Hash Tags” with a field name of hash_tags,
  • Text type called “Share Description” with a field name of buffer_desc
  • True / False type called “Lock Post” with a field name of buffer_lock_post

And assign this field group to your default Posts post type. I changed the Position setting to “Side” so it fits in the right rail on the edit screen like above.

Send to Buffer when Publishing Scheduled Posts

Next, we need to load the bufferapp-php library, and start a session. I put the bufferapp.php in my /includes/bufferapp/ folder like so in my functions.php file:

/**
 * Buffer App Library
 */
session_start();
require_once(get_template_directory().'/includes/libraries/bufferapp/bufferapp.php');

Finally, we need to trigger the logic that sends a scheduled post to Buffer. We’ll use the publish_future_post and draft_to_publish hooks to trigger our logic:

function buffer_schedule($post_id) {

	// if draft_to_publish calls this
	if (is_object ($post_id)) {
		// we get an object
		$object = $post_id;
		$id = $object->ID;
	// if publish_future_post calls this
	} else {
		// we get an id
		$object = get_post($post_id);
		$id = $post_id;
	}

	// check post type
	$post_type = get_post_type($id);

	// only do this for posts
	if ( 'post' == $post_type) {
		// okay proceed
	} else {
		// otherwise do nothing
		return;
	}

	// now check if buffer is permitted; if true, we skip this post
	// (this is the ACF field "buffer_lock_post" we created earlier)
	if (get_field('buffer_lock_post', $id)) return

	session_start();

	// now let's construct an excerpt...
	// if we have a manual buffer_desc in our ACF field for this post, use that
	if (get_field('buffer_desc', $id)) {
		$post_excerpt = get_field('buffer_desc', $id);
	} else {
		// otherwise, we should use the_excerpt from the post
		$post_excerpt = apply_filters('the_excerpt', get_post_field('post_excerpt', $id));
		// if there is no excerpt, we use the post title
		if (!$post_excerpt) $post_excerpt = $post_title;
	}

	// get the featured thumbnail
        $thumbnail_id = get_post_thumbnail_id($id);
	if ($thumbnail_id) {
		$thumbnail = wp_get_attachment_image_src( $thumbnail_id, 'post-thumbnail' );
	} else {
		$thumbnail = false;
	}

	// construct media array for buffer
	$media = array(
		'link'=> get_permalink($id),
		'description'=>$post_excerpt,
		'title'=>$post_excerpt,
		'picture'=>$thumbnail,
		'photo'=>$thumbnail,
		'thumbnail'=>$thumbnail
	);

	// by default, we'll attach categories as our hash tags
	// first, we check if there are any manually-entered hash tags
	// (this is the hash_tags ACF field we created earlier)
	if (get_field('hash_tags', $id)) {
		$term_list = get_field('hash_tags', $id);
	} else {
		// otherwise, let's get category terms
		// this will construct a list of hashtags like #term #term #term
		// using the slug of each term
		$term_list = '';
		$terms = get_the_terms($id, 'category');
		$count = count($terms);
		if ( $count > 0 ) {
			foreach ( $terms as $i=>$term ) {
				$hash_name = $term->slug;
				if ($i < $count-1) {
					$term_list .= '#'.$hash_name . " ";
				} else {
					$term_list .= '#'.$hash_name;
				}

			}
		}
	}

	// construct short link to inject into our sharing copy
	// we'll use this as the link to share with buffer
	$url = get_site_url().'/?p='.$id;

	// construct text to be shared
	$text = $post_excerpt . ' - ' .$url;

	// start a new buffer instance
	$buffer = new \BufferApp(BUFFER_CLIENT_ID, BUFFER_CLIENT_SECRET, null);

	// specify which profiles to queue to
	// you can find these IDs by looking at the URL when you one of your profiles
	// https://buffer.com/app/profile/YOUR_PROFILE_ID/buffer/queue/list
	$profiles = array(
		'PUT YOUR LINKEDIN BUFFER PROFILE ID HERE', // linkedin
		'PUT YOUR GOOGLE PLUS PROFILE ID HERE', // gplus
		'PUT YOUR FACEBOOK PROFILE ID HERE', // fb
		'PUT YOUR TWITTER PROFILE ID HERE', // twitter
	);

	foreach($profiles as $profile){
		// only certain profiles support hashtags, so let's only append our $term_list to those profiles
		if ($profile == 'PUT YOUR TWITTER PROFILE ID HERE' || $profile == 'PUT YOUR FACEBOOK PROFILE ID HERE') {
			$text = $post_excerpt . ' - '. $url . ' '.$term_list;
		} else {
			$text = $text;
		}
		$buffer->go('/updates/create', array(
			'text' => strip_tags($text),
			'media[title]'=> strip_tags(get_the_title($id)),
			'media[link]'=> get_permalink($id),
			'media[description]'=> strip_tags($post_excerpt),
			'media[picture]'=>  $thumbnail,
			'media[thumbnail]'=> $thumbnail,
			'profile_ids[]' => $profile
		));
	}

	// then, we need to lock this post from being posted to buffer in the future
	// you'll need to get the field ID of your buffer_lock_post field, and enter it here
	update_field('ENTER FIELD ID FOR BUFFER_LOCK_POST', 1, $id);

}
add_action('publish_future_post', 'buffer_schedule');
add_action('draft_to_publish', 'buffer_schedule', 10, 2 );

You’ll notice throughout that you’ll need to enter a few pieces of information from Buffer in the code above. First, you can find each social media account’s profile ID in the address bar when you’re editing their queues:

Second, you need to enter replace BUFFER_CLIENT_ID and BUFFER_CLIENT_SECRET with your own tokens. To get these, you need to create an app for Buffer. You’ll also need an access token. Normally, when you interact with the Buffer API, you need to authenticate with the API first via a callback URL to get the access token. However, after you register an app with Buffer, you’ll be given the client secret, client ID, and access token. Inside the bufferapp-php library, you need to supply the access token in lieu of the code that would ordinarily retrieve it from an authenticated session:

function retrieve_access_token() {
    $this->access_token = $_SESSION['oauth']['buffer']['access_token']; // replace this with a string that is your access token: "1/long-sequence-of-numbers-letters"

    if ($this->access_token) {
        $this->ok = true;
    }
}

Voila! Now when you publish posts, or when posts that are scheduled get published, WordPress will automatically send them over to Buffer in all your social queues.

You should see that the following sharing fields match up like so:

  • The post’s sharing title is the post title.
  • The post’s sharing description is the post’s excerpt + a short link to your post. In the case of LinkedIn and Twitter, hash tags are included.
  • If you’ve assigned a featured image to the post, that too will get sent along as the sharing image.
  • And finally, you can override the hash tags and sharing text by entering copy into the fields we set up with ACF in the post itself.

Have fun.


Viewing all articles
Browse latest Browse all 148

Trending Articles