Shortcode: Correct way of displaying a Twitter Share Button with or without counter

Every next day we need to show either twitter share or a twitter counter. This shortcode has the ability to do both. By default, it will tweet the current URL and Current page title. One good thing is, it would not load the twitter javascript on every page of the site but only on the page where shortcode is used. It will load it at footer instead of middle or start of the contents which as a very awful approach as it effects the page load time.

You can add one of the following codes where you want to display it.

Usage

[twitter url=’http://wpdevsnippets.com’]
[twitter via=’WPDevSnippets’]
[twitter countbox=”none/horizontal/vertical”]

Add following snippet to “functions.php”

Snippet

add_shortcode('twitter', 'wpds_twitter');
add_action('wp_head','enqueue_twitter_script');
function wpds_twitter( $atts, $content=null ){
	 
    extract(shortcode_atts(array(
        'url' => null,
	'title' => null,
        'counturl' => null,
        'via' => '', 		//WPDevSnippets
        'button' => '', 	// large, small
        'countbox' => 'none', // none, horizontal, vertical
    ), $atts));
	
	$output = '<a href="https://twitter.com/share" class="twitter-share-button" ';
	if(!empty($via))
		$output .= 'data-via="'.$via.'" ';
	if(!empty($button))
		$output .= 'data-size="'.$button.'" ';
	if(!empty($countbox))
		$output .= 'data-count="'.$countbox.'" ';
	if(!empty($url))
		$output .= 'data-url="'.$url.'" ';
	if(!empty($title))
		$output .= 'data-title="'.$title.'" ';
	$output .='>Tweet</a>';

        // load the twitter script
	wp_enqueue_script('twitter-widget-js');
    return $output;
}
function enqueue_twitter_script(){
	wp_register_script('twitter-widget-js','http://platform.twitter.com/widgets.js',null,true);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>