jQuery: creare un pulsante di condivisione personalizzato per Twitter

jQuery: creare un pulsante di condivisione personalizzato per Twitter

Con l'ultimo aggiornamento delle sue API, ora Twitter non consente più di effettuare richieste non autenticate. Quindi se vogliamo creare un pulsante Twitter personalizzato che visualizzi anche il numero di retweet dobbiamo combinare jQuery con PHP.

Il nostro script PHP esegue una richiesta GET a Twitter usando l'URL passatogli da jQuery e restituisce un oggetto JSON in cui la proprietà count mostra il numero di retweet.


<?php
header( 'Content-Type: application/json' );
$url = $_GET['url'];

if(filter_var( $url, FILTER_VALIDATE_URL ) ) {
	$baseURL = 'http://urls.api.twitter.com/1/urls/count.json?url=';
	$json = file_get_contents( $baseURL . $url );
	echo $json;
}

exit();
?>

Quindi creiamo il codice HTML usando dei segnaposto nell'URL di Twitter che verranno sostituiti da jQuery. L'elemento con classe count mostrerà il numero di condivisioni.


<a href="https://twitter.com/intent/tweet?url=#url&via=#via&text=#text" class="twitter-btn">
	<span class="count">0</span>
</a>

Il codice jQuery è il seguente:


(function( $ ) {
	$.fn.twitterShare = function( options ) {
	
		options = $.extend({
			countElement: ".count",
			ajaxURL: "retweets.php",
			shareURL: location.href,
			popupWidth: "500",
			popupHeight: "400"
			via: "gabromanato",
			text: document.title
		}, options);
		
		var _addCommas = function( number ) {
			if ( number.length > 3 ) {
					var mod = number.length % 3;
					var output = ( mod > 0 ? ( number.substring( 0,mod ) ) : "" );
					for ( var i=0 ; i < Math.floor( number.length / 3 ); i++ ) {
						if ( ( mod == 0 ) && ( i == 0 ) ) {
							output += number.substring( mod + 3 * i, mod + 3 * i + 3 );
						} else {
							output+= ',' + number.substring( mod + 3 * i, mod + 3 * i + 3 );	
						}
					}
				return ( output );
			} else {
				return number;
			}
		};
		
		return this.each(function() {
			var $element = $( this ),
				$count = $element.find( options.countElement ),
				href = $element.attr( "href" );
			
			$element.attr( "href", href.replace( "#url", options.shareURL ).
				replace( "#via", options.via ). replace( "#text", options.text ) );
			
			$.getJSON( options.ajaxURL, { url: options.shareURL }, function( data ) {
				var count = data.count;
				$count.text( _addCommas( count ) );
			});
			
			$element.on( "click", function( e ) {
				e.preventDefault();
				var uri = $element.attr( "href" );
				
				window.open( uri, "", "width=" + options.popupWidth + ",height=" + options.popupHeight );
			});
		
		});
	
	};

})( jQuery );

Il nostro plugin non fa altro che effettuare una richiesta AJAX al nostro script PHP per ottenere il numero di condivisioni per l'URL specificato nell'opzione shareURL (il suo valore predefinito è la pagina corrente). Il percorso al file PHP può essere personalizzato modificando l'opzione ajaxURL.

Il plugin inoltre sostituisce i segnaposto #parametro i dati specificati nelle sue opzioni e apre una finestra popup per la condivisione le cui dimensioni possono essere specificate nelle opzioni popupWidth e popupHeight. L'elemento contenuto nell'opzione countElement è un elemento jQuery che mostrerà il numero totale di condivisioni.

Ecco come si usa il plugin:


$( document ).ready(function() {
	$( ".post" ).each(function() {
		var $post = $( this );
		var permalink = $post.find( ".post-title a" ).attr( "href" );
		var text = $post.find( ".post-title a" ).text();
		var $twitterBtn = $post.find( ".twitter-btn" );
		
		$twitterBtn.twitterShare({
			shareURL: permalink,
			text: text
		});
	});
});

In questo caso abbiamo simulato la presenza di una pagina contenente vari post, ognuno con il suo permalink di cui vogliamo mostrare il numero di condivisioni unitamente al testo del tweet che sarà il titolo del post.

Torna su