Come posso visualizzare il numero di retweet nei post e nelle pagine di WordPress?

Come posso visualizzare il numero di retweet nei post e nelle pagine di WordPress?

Inserire il numero di retweet nei post e nelle pagine di WordPress si rivela come un'operazione alquanto semplice.

Definiamo il seguente codice in functions.php:


function my_get_tweets_count( $url ) {
	$base_url = 'http://urls.api.twitter.com/1/urls/count.json?url=';
	$count = '0';
	if( filter_var( $url, FILTER_VALIDATE_URL ) ) {
		$api_url = $base_url . $url;
		$response = wp_remote_get( $api_url, array( 'timeout' => 2 ) );
		if ( !is_wp_error( $response ) ) {
			$json = json_decode( $response['body'] );
			$count = $json->count;
		}
	}
		
	return $count;
}

function my_retweets() {
	global $post;
	$permalink = get_permalink( $post->ID );
	$tweets_count = my_get_tweets_count( $permalink );
	$html = '<span class="retweets">' . $tweets_count . '</span>';
	
	return $html;
}

add_shortcode( 'my-retweets', 'my_retweets' );

Abbiamo creato il seguente shortcode:


[my-retweets]

Dato che la funzione principale non accetta parametri, possiamo anche inserirla direttamente nel nostro tema:


<?php echo my_retweets(); ?>

Torna su