Creating a WordPress shortcode that uses ACF, Twitter sharing and the Google URL Shortener API

We’ve created a simple block quote with a quote, name and picture for blog posts. This time a client needed to set up the quotes through the CMS, place it anywhere in the post using a simple shortcode, include a Twitter share button to share the quote and finally utilise the Google URL shortener API to keep the page link short for Twitter.

Setting up your Advanced Custom Fields

We use a premium plugin called Advanced Custom Fields that lets us add additional meta data fields to posts, pages and more. There are free alternatives like the Types plugin that you can use to add meta fields to your posts. You can also use the built in WordPress custom fields if you don’t need nice looking CMS integration.

For those using ACF you need to set up a new field group and add a repeater field called ‘Quotes’, in that repeater you’ll need to add 3 sub fields for ‘Quote’, ‘Name’ and ‘Quote Image’.

setting-up-acf

Once you’ve added your ACF fields and told ACF to show the fields on your posts you can visit an individual post and add a new quote.

add-quote-to-post

Let’s add our shortcode

Now we have some custom fields to get information from we can start adding the following code to your theme functions.php file. Once you’ve found your file the first thing we need to do is to create our shortcode. This snippet of code tells WordPress to allow you to use the [quote]. It looks for additional attributes ($atts) but we’ll add those later. If you save your file and place the [quote] shortcode into a post your should see the “Making a start” line appear.

function kinoshortcode( $atts ) {
	return 'Making a start';
}

add_shortcode( 'quote', 'kinoshortcode' );

Getting some field data from ACF

This is where we modify our previous function to make it do something useful. We need to look what post the shortcode was used on and look to see if we have any quotes then let the user tell the shortcode what quote they would like to show. Each time you add a new row, or quote, to ACF they have an number next to them to show what order they are in. We are going to use that order number to represent our quote ID, so quote 1 will be ID 1, quote 3 will be ID 3, etc… This will let the user drag and drop the quotes in order of importance and still show them the ID to use.

function kinoshortcode( $atts ) {
	// Get the ID of the post the shortcode was used on
	$whatpost = get_the_ID();

	// Get an array of all the ACF quotes used on the post using that ID
	$allquotes = get_field('quotes', $whatpost);

	// Get the ID attribute from the shortcode [quote id="1"] for example
	$id = $atts['id'];
	
	// Return the chosen quote back to the page
	// I've chosen to return a blockquote with a 'postquote' class so it can be styled. You can return whatever elements you need
	return '<blockquote class="postquote"><p>
		<img src="' . $allquotes[$id-1][quote_image] . '"/>'
		. sanitize_text_field( $allquotes[$id-1][quote]) .
		'<span>'.$allquotes[$id-1][name].'</span>
		</p&gt
		<a class="twitter-share-button"
			href="https://twitter.com/intent/tweet?text='.$tweetable.'&url='.$shortlink.'"
			data-size="large">
		Tweet</a>
		</blockquote>';
}

add_shortcode( 'quote', 'kinoshortcode' );

This function should no replace the [quote id=”1″] with the following HTML markup containing the quote information for quote 1.

<blockquote class="postquote">
	<p>
		<img src="http://www.example.com/this-is-your-image.jpg"/>
		This is the actual quote message
		<span>Joe Blogs, Kino Creative</span>
	</p&gt
</blockquote>';

You can leave it at that and start styling your elements using CSS to improve the appearance or you can continue and we’ll add a twitter share button and share a link using Google’s URL shortener.

Tweeting on Twitter and shortened URLs by Google

Sharing a quote with your followers on twitter is a great way to get your site noticed. You can add a twitter share button using Twitter’s own share button. In this example we’ve shortened the length of the code to fit in Twitter’s character limit. The URL is shortened using Google’s URL shortener to make it useful when sharing a link to the post.

To use the Google URL shortener you’ll need to sign up for a Google Developers account as we will need a Google API key, Google have put together their own documentation on getting started with the URL shortener API. Once you have your API key you can use it in the previous example with a few new lines.

function kinoshortcode( $atts ) {
	$whatpost = get_the_ID();
	$allquotes = get_field('quotes', $whatpost);
	$id = $atts['id'];

	// Get the permalink the for post the shortcode appears on
	$permalink = get_permalink();
	
        // Save a string containing the quote but use sanitize_text_field() to convert any tags of characters to a usable format
	$tweetable = sanitize_text_field( $allquotes[$id-1][quote]);

	// Use substr() to trim the string to 110 usable characters and add an ellipsis after
	$tweetable = substr($tweetable,0,110).'...';
	
	// This is the URL shortener link. Replace the 0's with YOUR API key!
	$url = 'https://www.googleapis.com/urlshortener/v1/url?key=00000000000000000000000000000000';

	// POST the post URL to Google and return the JSON data containing the short URL
	$http = new WP_Http();
	$headers = array('Content-Type' => 'application/json');
	$result = $http->request($url, array( 'method' => 'POST', 'body' => '{"longUrl": "' . $permalink . '"}', 'headers' => $headers));
	$result = json_decode($result['body']);

	// This $shortlink variable should now contain the short URL for your 
	$shortlink = $result->id;
	
	// Twitter passes the tweet content as a URL query string. urlencode() will convert all characters, like spaces to a format URLs can use
	$tweetable = urlencode( $tweetable );
	
	// We return our blockquote, this time with a Twitter button and our shortened post URL  
	return '<blockquote class="postquote"><p>
		<img src="' . $allquotes[$id-1][quote_image] . '"/>'
		. sanitize_text_field( $allquotes[$id-1][quote]) .
		'<span>'.$allquotes[$id-1][name].'</span>
		</p&gt
		<a class="twitter-share-button"
			href="https://twitter.com/intent/tweet?text='.$tweetable.'&url='.$shortlink.'"
			data-size="large">
		Tweet</a>
		</blockquote>';
}

add_shortcode( 'quote', 'kinoshortcode' );

TL;DR Putting it all together

This is what the finished function looks like when we bring all the functionality together. Hopefully this will let you create your own block quote shortcode that uses ACF, Twitter sharing and the Google URL shortener.

function kinoshortcode( $atts ) {
	$whatpost = get_the_ID();
	$permalink = get_permalink();
	$allquotes = get_field('quotes', $whatpost);
	$id = $atts['id'];
	$tweetable = sanitize_text_field( $allquotes[$id-1][quote]);
	$tweetable = substr($tweetable,0,110).'...';
			
	$url = 'https://www.googleapis.com/urlshortener/v1/url?key=00000000000000000000000000000000';

	$http = new WP_Http();
	$headers = array('Content-Type' => 'application/json');
	$result = $http->request($url, array( 'method' => 'POST', 'body' => '{"longUrl": "' . $permalink . '"}', 'headers' => $headers));
	$result = json_decode($result['body']);
	$shortlink = $result->id;
	
	$tweetable = urlencode( $tweetable );
	
	return '<blockquote class="postquote"><p>
		<img src="' . $allquotes[$id-1][quote_image] . '"/>'
		. sanitize_text_field( $allquotes[$id-1][quote]) .
		'<span>'.$allquotes[$id-1][name].'</span>
		</p&gt
		<a class="twitter-share-button"
			href="https://twitter.com/intent/tweet?text='.$tweetable.'&url='.$shortlink.'"
			data-size="large">
		Tweet</a>
		</blockquote>';
}

add_shortcode( 'quote', 'kinoshortcode' );

Here is a bit of bonus CSS to tidy up the look of the quote, but you can apply your own styling to the “postquote” class.

.postquote {
	display: inline-block;
	margin-bottom: 0px;
}

.postquote p {
	font-size: 16px;
 	color: #343536;
	line-height: 1.5;
	font-style: italic;
}

.postquote img {
	float: left;
	padding-right: 20px;
	margin-bottom: 10px;
	width: 120px;
	height: 150px;
}
	
.postquote span {
	font-weight: bold;
	font-style: normal;
	display: block;
}

.postquote .twitter-tweet-button {
	float: right;
}

#s-share-buttons {
	text-align: right;
	margin-top: 20px;		
}

Hopefully you’ve found some useful code here on our blog post, if you know anyone who might find this useful please share this post. Keep following our blog for more useful WordPress coding tips and tricks.